#!/usr/bin/env python3 """ 概要: 区間[0, 1]におけるsqrt(1-x^2)の中点リーマン和による積分ベンチマークスクリプトです。 詳細説明: 厳密な積分値はpi/4であるため、各手法は pi = 4 * 積分値 を計算し、その誤差を報告します。 NumPy、Numba、CuPyなどのオプションの手法は、利用できない場合はスキップされます。 関連リンク: pi_riemann_benchmark_linux_usage """ from __future__ import annotations import argparse import math import statistics import time from collections.abc import Callable def pi_for(nmax: int) -> float: """ 概要: forループを使用して円周率を計算します。 引数: :param nmax: 中点サンプルの数 :type nmax: int 戻り値: :returns: 計算された円周率の近似値 :rtype: float """ dx = 1.0 / nmax total = 0.0 for i in range(nmax): x = (i + 0.5) * dx total += math.sqrt(1.0 - x * x) return 4.0 * dx * total def pi_sum_generator(nmax: int) -> float: """ 概要: ジェネレータ式とsum関数を使用して円周率を計算します。 引数: :param nmax: 中点サンプルの数 :type nmax: int 戻り値: :returns: 計算された円周率の近似値 :rtype: float """ dx = 1.0 / nmax total = sum( math.sqrt(1.0 - ((i + 0.5) * dx) ** 2) for i in range(nmax) ) return 4.0 * dx * total def pi_sum_listcomp(nmax: int) -> float: """ 概要: リスト内包表記とsum関数を使用して円周率を計算します。 詳細説明: 意図的にリストをメモリ上に作成し、メモリ割り当てのオーバーヘッドを露出させます。 引数: :param nmax: 中点サンプルの数 :type nmax: int 戻り値: :returns: 計算された円周率の近似値 :rtype: float """ dx = 1.0 / nmax # Deliberately materializes the list: this exposes allocation overhead. values = [math.sqrt(1.0 - ((i + 0.5) * dx) ** 2) for i in range(nmax)] return 4.0 * dx * sum(values) def make_numpy() -> Callable[[int], float] | None: """ 概要: NumPyを使用する計算関数を作成して返します。 詳細説明: NumPyがインポートできない場合はNoneを返します。 戻り値: :returns: NumPyを使用した円周率計算関数またはNone :rtype: Callable[[int], float] | None """ try: import numpy as np except ImportError: return None def pi_numpy(nmax: int) -> float: """ 概要: NumPyを使用して円周率を計算します。 引数: :param nmax: 中点サンプルの数 :type nmax: int 戻り値: :returns: 計算された円周率の近似値 :rtype: float """ dx = 1.0 / nmax x = (np.arange(nmax, dtype=np.float64) + 0.5) * dx return float(4.0 * dx * np.sum(np.sqrt(1.0 - x * x))) return pi_numpy def make_numba() -> Callable[[int], float] | None: """ 概要: Numbaを使用する計算関数を作成して返します。 詳細説明: Numbaがインポートできない場合はNoneを返します。計測前にJITコンパイルのウォームアップを行います。 戻り値: :returns: Numbaを使用した円周率計算関数またはNone :rtype: Callable[[int], float] | None """ try: import numba except ImportError: return None @numba.njit(cache=True) def pi_numba(nmax: int) -> float: """ 概要: Numbaを使用して円周率を計算します。 引数: :param nmax: 中点サンプルの数 :type nmax: int 戻り値: :returns: 計算された円周率の近似値 :rtype: float """ dx = 1.0 / nmax total = 0.0 for i in range(nmax): x = (i + 0.5) * dx total += math.sqrt(1.0 - x * x) return 4.0 * dx * total # Compile before the timed benchmark; JIT startup is reported separately. t0 = time.perf_counter() pi_numba(1) print(f"Numba JIT warm-up: {time.perf_counter() - t0:.6f} s") return pi_numba def make_cupy() -> Callable[[int], float] | None: """ 概要: CuPyを使用する計算関数を作成して返します。 詳細説明: CuPyがインポートできないかGPUが利用できない場合はNoneを返します。計測前にカーネルのウォームアップを行います。 戻り値: :returns: CuPyを使用した円周率計算関数またはNone :rtype: Callable[[int], float] | None """ try: import cupy as cp cp.cuda.runtime.getDeviceCount() except Exception: return None def pi_cupy(nmax: int) -> float: """ 概要: CuPyを使用して円周率を計算します。 引数: :param nmax: 中点サンプルの数 :type nmax: int 戻り値: :returns: 計算された円周率の近似値 :rtype: float """ dx = 1.0 / nmax # Generation, reduction and scalar transfer are included in elapsed time. x = (cp.arange(nmax, dtype=cp.float64) + 0.5) * dx result = 4.0 * dx * cp.sum(cp.sqrt(1.0 - x * x)) return float(result.get()) # synchronizes the GPU before timing stops # Allocate and compile kernels outside the measurement, as for Numba. pi_cupy(1) return pi_cupy def benchmark(name: str, func: Callable[[int], float], nmax: int, repeat: int) -> None: """ 概要: 指定された計算関数のベンチマークを実行し、結果を表示します。 引数: :param name: 手法の名前 :type name: str :param func: 円周率を計算する関数 :type func: Callable[[int], float] :param nmax: 中点サンプルの数 :type nmax: int :param repeat: 実行回数 :type repeat: int 戻り値: :returns: なし :rtype: None """ times: list[float] = [] value = 0.0 for _ in range(repeat): t0 = time.perf_counter() value = func(nmax) times.append(time.perf_counter() - t0) print( f"{name:18s} pi={value:.15f} " f"abs.error={abs(value - math.pi):.3e} " f"median={statistics.median(times):.6f} s " f"min={min(times):.6f} s" ) def main() -> None: """ 概要: コマンドライン引数を解析し、ベンチマークを実行します。 詳細説明: 引数としてサンプリング数や繰り返し回数、実行する手法を受け取ります。 戻り値: :returns: なし :rtype: None """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--nmax", type=int, default=1_000_000, help="number of midpoint samples (default: 1000000)") parser.add_argument("--repeat", type=int, default=3, help="timed repetitions per method (default: 3)") parser.add_argument("--methods", nargs="+", default=["all"], choices=["all", "for", "generator", "listcomp", "numpy", "numba", "cupy"], help="methods to run (default: all)") args = parser.parse_args() if args.nmax < 1 or args.repeat < 1: parser.error("--nmax and --repeat must be positive") methods: dict[str, Callable[[int], float] | None] = { "for": pi_for, "generator": pi_sum_generator, "listcomp": pi_sum_listcomp, "numpy": make_numpy(), "numba": make_numba(), "cupy": make_cupy(), } selected = list(methods) if "all" in args.methods else args.methods print(f"Midpoint Riemann sum: nmax={args.nmax:,}, repeat={args.repeat}") for name in selected: func = methods[name] if func is None: print(f"{name:18s} skipped (package or usable GPU unavailable)") else: benchmark(name, func, args.nmax, args.repeat) if __name__ == "__main__": main()