pi_riemann_benchmark.py ダウンロード/コピー

pi_riemann_benchmark.py をダウンロード

pi_riemann_benchmark.py
pi_riemann_benchmark.py
  1#!/usr/bin/env python3
  2"""
  3概要:
  4    区間 [0, 1] における sqrt(1 - x^2) の中点リーマン和による積分ベンチマーク。
  5
  6詳細説明:
  7    正確な積分値は pi/4 であるため、各メソッドは pi = 4 * I を計算し、その誤差を報告します。
  8    NumPy、Numba、CuPy といった追加のメソッドは、利用できない場合はスキップされます。
  9
 10関連リンク:
 11    pi_riemann_benchmark_usage
 12"""
 13
 14from __future__ import annotations
 15
 16import argparse
 17import math
 18import statistics
 19import time
 20from collections.abc import Callable
 21
 22
 23def pi_for(nmax: int) -> float:
 24    """
 25    概要:
 26        forループを用いて円周率を計算します。
 27    詳細説明:
 28        中点リーマン和のアルゴリズムを標準のforループで実装しています。
 29    引数:
 30        :param nmax: 分割数。
 31        :type nmax: int
 32    戻り値:
 33        :returns: 計算された円周率の近似値。
 34        :rtype: float
 35    """
 36    dx = 1.0 / nmax
 37    total = 0.0
 38    for i in range(nmax):
 39        x = (i + 0.5) * dx
 40        total += math.sqrt(1.0 - x * x)
 41    return 4.0 * dx * total
 42
 43
 44def pi_sum_generator(nmax: int) -> float:
 45    """
 46    概要:
 47        ジェネレータ式とsum関数を用いて円周率を計算します。
 48    詳細説明:
 49        中点リーマン和の各項をジェネレータ式で生成し、組み込みのsum関数で合計します。
 50    引数:
 51        :param nmax: 分割数。
 52        :type nmax: int
 53    戻り値:
 54        :returns: 計算された円周率の近似値。
 55        :rtype: float
 56    """
 57    dx = 1.0 / nmax
 58    total = sum(
 59        math.sqrt(1.0 - ((i + 0.5) * dx) ** 2) for i in range(nmax)
 60    )
 61    return 4.0 * dx * total
 62
 63
 64def pi_sum_listcomp(nmax: int) -> float:
 65    """
 66    概要:
 67        リスト内包表記を用いて円周率を計算します。
 68    詳細説明:
 69        リストを意図的にメモリ上に展開し、メモリアロケーションのオーバーヘッドを評価します。
 70    引数:
 71        :param nmax: 分割数。
 72        :type nmax: int
 73    戻り値:
 74        :returns: 計算された円周率の近似値。
 75        :rtype: float
 76    """
 77    dx = 1.0 / nmax
 78    # Deliberately materializes the list: this exposes allocation overhead.
 79    values = [math.sqrt(1.0 - ((i + 0.5) * dx) ** 2) for i in range(nmax)]
 80    return 4.0 * dx * sum(values)
 81
 82
 83def make_numpy() -> Callable[[int], float] | None:
 84    """
 85    概要:
 86        NumPyを利用した円周率計算関数を作成して返します。
 87    詳細説明:
 88        NumPyがインポート可能な場合は、ベクトル化された計算関数を返します。
 89        インポートできない場合はNoneを返します。
 90    戻り値:
 91        :returns: NumPyを用いた円周率計算関数、またはNone。
 92        :rtype: Callable[[int], float] | None
 93    """
 94    try:
 95        import numpy as np
 96    except ImportError:
 97        return None
 98
 99    def pi_numpy(nmax: int) -> float:
100        """
101        概要:
102            NumPyを用いて円周率を計算します。
103        引数:
104            :param nmax: 分割数。
105            :type nmax: int
106        戻り値:
107            :returns: 計算された円周率の近似値。
108            :rtype: float
109        """
110        dx = 1.0 / nmax
111        x = (np.arange(nmax, dtype=np.float64) + 0.5) * dx
112        return float(4.0 * dx * np.sum(np.sqrt(1.0 - x * x)))
113
114    return pi_numpy
115
116
117def make_numba() -> Callable[[int], float] | None:
118    """
119    概要:
120        Numbaを利用した円周率計算関数を作成して返します。
121    詳細説明:
122        Numbaがインポート可能な場合は、JITコンパイルされた関数を返します。
123        ベンチマーク計測の前にウォームアップ実行を行います。
124        インポートできない場合はNoneを返します。
125    戻り値:
126        :returns: Numbaを用いた円周率計算関数、またはNone。
127        :rtype: Callable[[int], float] | None
128    """
129    try:
130        import numba
131    except ImportError:
132        return None
133
134    @numba.njit(cache=True)
135    def pi_numba(nmax: int) -> float:
136        """
137        概要:
138            Numbaを用いて円周率を計算します。
139        引数:
140            :param nmax: 分割数。
141            :type nmax: int
142        戻り値:
143            :returns: 計算された円周率の近似値。
144            :rtype: float
145        """
146        dx = 1.0 / nmax
147        total = 0.0
148        for i in range(nmax):
149            x = (i + 0.5) * dx
150            total += math.sqrt(1.0 - x * x)
151        return 4.0 * dx * total
152
153    # Compile before the timed benchmark; JIT startup is reported separately.
154    t0 = time.perf_counter()
155    pi_numba(1)
156    print(f"Numba JIT warm-up: {time.perf_counter() - t0:.6f} s")
157    return pi_numba
158
159
160def make_cupy() -> Callable[[int], float] | None:
161    """
162    概要:
163        CuPyを利用した円周率計算関数を作成して返します。
164    詳細説明:
165        CuPyがインポート可能でGPUが利用できる場合は、CUDAを用いた計算関数を返します。
166        カーネルのコンパイルを行うため、ウォームアップ実行を行います。
167        利用できない場合はNoneを返します。
168    戻り値:
169        :returns: CuPyを用いた円周率計算関数、またはNone。
170        :rtype: Callable[[int], float] | None
171    """
172    try:
173        import cupy as cp
174        cp.cuda.runtime.getDeviceCount()
175    except Exception:
176        return None
177
178    def pi_cupy(nmax: int) -> float:
179        """
180        概要:
181            CuPyを用いて円周率を計算します。
182        引数:
183            :param nmax: 分割数。
184            :type nmax: int
185        戻り値:
186            :returns: 計算された円周率の近似値。
187            :rtype: float
188        """
189        dx = 1.0 / nmax
190        # Generation, reduction and scalar transfer are included in elapsed time.
191        x = (cp.arange(nmax, dtype=cp.float64) + 0.5) * dx
192        result = 4.0 * dx * cp.sum(cp.sqrt(1.0 - x * x))
193        return float(result.get())  # synchronizes the GPU before timing stops
194
195    # Allocate and compile kernels outside the measurement, as for Numba.
196    pi_cupy(1)
197    return pi_cupy
198
199
200def benchmark(name: str, func: Callable[[int], float], nmax: int, repeat: int) -> None:
201    """
202    概要:
203        指定された関数でベンチマークを実行し、結果を出力します。
204    詳細説明:
205        各メソッドについて指定回数実行し、円周率の計算結果、絶対誤差、中央値、最小実行時間を出力します。
206    引数:
207        :param name: ベンチマーク対象のメソッド名。
208        :type name: str
209        :param func: 円周率を計算する関数。
210        :type func: Callable[[int], float]
211        :param nmax: 分割数。
212        :type nmax: int
213        :param repeat: 計測の繰り返し回数。
214        :type repeat: int
215    戻り値:
216        :returns: なし。
217        :rtype: None
218    """
219    times: list[float] = []
220    value = 0.0
221    for _ in range(repeat):
222        t0 = time.perf_counter()
223        value = func(nmax)
224        times.append(time.perf_counter() - t0)
225
226    print(
227        f"{name:18s} pi={value:.15f}  "
228        f"abs.error={abs(value - math.pi):.3e}  "
229        f"median={statistics.median(times):.6f} s  "
230        f"min={min(times):.6f} s"
231    )
232
233
234def main() -> None:
235    """
236    概要:
237        スクリプトのエントリポイントです。
238    詳細説明:
239        コマンドライン引数を解析し、指定されたメソッドで円周率計算のベンチマークを実行します。
240    戻り値:
241        :returns: なし。
242        :rtype: None
243    """
244    parser = argparse.ArgumentParser(description=__doc__)
245    parser.add_argument("--nmax", type=int, default=1_000_000,
246                        help="number of midpoint samples (default: 1000000)")
247    parser.add_argument("--repeat", type=int, default=3,
248                        help="timed repetitions per method (default: 3)")
249    parser.add_argument("--methods", nargs="+", default=["all"],
250                        choices=["all", "for", "generator", "listcomp", "numpy", "numba", "cupy"],
251                        help="methods to run (default: all)")
252    args = parser.parse_args()
253    if args.nmax < 1 or args.repeat < 1:
254        parser.error("--nmax and --repeat must be positive")
255
256    methods: dict[str, Callable[[int], float] | None] = {
257        "for": pi_for,
258        "generator": pi_sum_generator,
259        "listcomp": pi_sum_listcomp,
260        "numpy": make_numpy(),
261        "numba": make_numba(),
262        "cupy": make_cupy(),
263    }
264    selected = list(methods) if "all" in args.methods else args.methods
265
266    print(f"Midpoint Riemann sum: nmax={args.nmax:,}, repeat={args.repeat}")
267    for name in selected:
268        func = methods[name]
269        if func is None:
270            print(f"{name:18s} skipped (package or usable GPU unavailable)")
271        else:
272            benchmark(name, func, args.nmax, args.repeat)
273
274
275if __name__ == "__main__":
276    main()