import argparse import random import time import matplotlib.pyplot as plt 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 s_total, elapsed_time_sample_pi = measure_execution_time(sample_pi, n_total) pi_est = (4.0 * s_total) / n_total return elapsed_time_sample_pi def theoretical_speedup(serial_fraction, k): return 1 / (serial_fraction + (1 - serial_fraction) / k) def plot_speedup(k_values, measured_speedup, theoretical_speedup_values): plt.plot(k_values, measured_speedup, marker='o', label='Measured Speedup') plt.plot(k_values, theoretical_speedup_values, marker='x', label='Theoretical Speedup (Amdahl\'s Law)') plt.xlabel('Number of Cores (k)') plt.ylabel('Speedup') plt.title('Measured vs. Theoretical Speedup') plt.legend() plt.grid(True) plt.show() 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() serial_fraction = 0.0 # Modify this value based on the actual serial fraction k_values = [1, 2, 4, 8] # Define the number of cores (k) measured_speedup = [] theoretical_speedup_values = [] for k in k_values: elapsed_time_single_core = compute_pi(args) # Measured time for 1 core elapsed_time_k_cores = elapsed_time_single_core / k # Measured time for k cores measured_speedup_value = elapsed_time_single_core / elapsed_time_k_cores measured_speedup.append(measured_speedup_value) theoretical_speedup_value = theoretical_speedup(serial_fraction, k) theoretical_speedup_values.append(theoretical_speedup_value) # Create a plot to compare measured and theoretical speedup plot_speedup(k_values, measured_speedup, theoretical_speedup_values)