defestimate_pi( n_points: int, show_estimate: bool, ) -> None:""" Simple Monte Carlo Pi estimation calculation. Parameters ---------- n_points number of random numbers used to for estimation. show_estimate if True, will show the estimation of Pi, otherwise will not output anything. """ within_circle = 0for _ in range(n_points): x, y = (random.uniform(-1, 1) for v in range(2)) radius_squared = x**2 + y**2if radius_squared <= 1: within_circle += 1 pi_estimate = 4 * within_circle / n_points ifnot show_estimate: print("Final Estimation of Pi=", pi_estimate) defrun_test( n_points: int, n_repeats: int, only_time: bool, ) -> None:""" Perform the tests and measure required time. Parameters ---------- n_points number of random numbers used to for estimation. n_repeats number of times the test is repeated. only_time if True will only print the time, otherwise will also show the Pi estimate and a neat formatted time. """ start_time = time.time() for _ in range(n_repeats): estimate_pi(n_points, only_time) if only_time: print(f"{(time.time() - start_time)/n_repeats:.4f}") else: print( f"Estimating pi took {(time.time() - start_time)/n_repeats:.4f} seconds per run." )
测试多个 Python 版本的最简单方法是使用 Docker。 要使用 Docker需要安装它。在 Linux 和 Mac 中它相对容易,在 Windows 中稍微复杂一些。虽然Docker中运行会有一些效率的降低,但是测试都在Docker进行,所以误差就可以忽略了。要在容器化 Python 环境中运行本地脚本,可以使用下面命令:
deftest_version(image: str) -> float:""" Run single_test on Python Docker image. Parameter --------- image full name of the the docker hub Python image. Returns ------- run_time runtime in seconds per test loop. """ output = subprocess.run(['docker','run','-it','--rm','-v',f'{cwd}/{SCRIPT}:/{SCRIPT}', image,'python',f'/{SCRIPT}','--n_points', str(N_POINTS),'--n_repeats', str(N_REPEATS),'--only-time', ], capture_output=True, text=True, ) avg_time = float(output.stdout.strip())return avg_time# Get test time for current Python version base_time = test_version(NEW_IMAGE['image']) print(f"The new {NEW_IMAGE['name']} took {base_time} seconds per run.n")# Compare to previous Python versionsfor item in TEST_IMAGES: ttime = test_version(item['image']) print(f"{item['name']} took {ttime} seconds per run."f"({NEW_IMAGE['name']} is {(ttime / base_time) - 1:.1%} faster)" )
评论