#!/usr/bin/env python3 """ 概要: 区間 [0, 1] における sqrt(1 - x^2) の中点リーマン和による積分ベンチマーク。 詳細説明: 正確な積分値は pi/4 であるため、各メソッドは pi = 4 * I を計算し、その誤差を報告します。 NumPy、Numba、CuPy といった追加のメソッドは、利用できない場合はスキップされます。 関連リンク: pi_riemann_benchmark_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ループを用いて円周率を計算します。 詳細説明: 中点リーマン和のアルゴリズムを標準の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関数を用いて円周率を計算します。 詳細説明: 中点リーマン和の各項をジェネレータ式で生成し、組み込みの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: """ 概要: リスト内包表記を用いて円周率を計算します。 詳細説明: リストを意図的にメモリ上に展開し、メモリアロケーションのオーバーヘッドを評価します。 引数: :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がインポート可能な場合は、JITコンパイルされた関数を返します。 ベンチマーク計測の前にウォームアップ実行を行います。 インポートできない場合はNoneを返します。 戻り値: :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が利用できる場合は、CUDAを用いた計算関数を返します。 カーネルのコンパイルを行うため、ウォームアップ実行を行います。 利用できない場合は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()