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