import argparse import random from math import pi import time def sample_pi(n): s = 0 for i in range(n): x = random.random() y = random.random() if x**2 + y**2 <= 1.0: s += 1 return s def measure_execution_time(function, *args): start_time = time.time() result = function(*args) end_time = time.time() elapsed_time = end_time - start_time return result, elapsed_time def compute_pi(args): random.seed(1) n_total = args.steps # Measure the time for sample_pi s_total, elapsed_time_sample_pi = measure_execution_time(sample_pi, n_total) pi_est = (4.0 * s_total) / n_total print(" Steps\tSuccess\tPi est.\tError") print("%6d\t%7d\t%1.5f\t%1.5f" % (n_total, s_total, pi_est, pi - pi_est)) print("Time taken for sample_pi: {:.4f} seconds".format(elapsed_time_sample_pi)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Compute Pi using Monte Carlo simulation') parser.add_argument('--steps', '-s', default=1000, type=int, help='Number of steps in the Monte Carlo simulation') args = parser.parse_args() # Measure the time for the entire compute_pi function _, elapsed_time_compute_pi = measure_execution_time(compute_pi, args) print("Time taken for compute_pi: {:.4f} seconds".format(elapsed_time_compute_pi))