ufunc_benchmark.py ダウンロード/コピー
ufunc_benchmark.py
ufunc_benchmark.py
1"""
2概要:
3 要素ごとの計算方法を比較するベンチマークスクリプトです。
4詳細説明:
5 Python、NumPy、numpy.vectorize、およびNumbaの実行速度を比較します。
6 使用方法として python ufunc_benchmark.py -n 1000000 --repeat 5 のように実行します。
7 NumPyは必須ですが、Numbaはオプションです。GPUや並列処理は使用しません。
8 すべての実装において float64 型で sin(x) + x*x + 1.0 を計算し、配列を返します。
9 入力の作成、ウォームアップ、結果の検証、表示にかかる時間はトライアルの計測には含まれず、
10 出力のメモリ割り当てや中間配列の作成はトライアルの計測に含まれます。
11関連リンク:
12 ufunc_benchmark_usage
13"""
14import argparse
15import math
16import platform
17from statistics import median
18from time import perf_counter
19import numpy as np
20
21
22def scalar_function(x):
23 """
24 概要:
25 スカラー値に対して数式を計算します。
26 引数:
27 :param x: 計算対象の入力数値
28 :type x: float
29 戻り値:
30 :returns: 計算結果の数値
31 :rtype: float
32 """
33 return math.sin(x) + x*x + 1.0
34
35
36def python_loop(x):
37 """
38 概要:
39 Pythonのforループを使用して配列の各要素を計算します。
40 引数:
41 :param x: 計算対象の入力配列
42 :type x: numpy.ndarray
43 戻り値:
44 :returns: 計算結果が格納された新しい配列
45 :rtype: numpy.ndarray
46 """
47 out = np.empty_like(x)
48 for i in range(x.size):
49 out[i] = scalar_function(float(x[i]))
50 return out
51
52
53def python_listcomp(x):
54 """
55 概要:
56 Pythonのリスト内包表記を使用して配列の各要素を計算します。
57 引数:
58 :param x: 計算対象の入力配列
59 :type x: numpy.ndarray
60 戻り値:
61 :returns: 計算結果が格納された新しい配列
62 :rtype: numpy.ndarray
63 """
64 return np.array([scalar_function(float(t)) for t in x], dtype=np.float64)
65
66
67def numpy_ufunc(x):
68 """
69 概要:
70 NumPyのufuncを使用して配列全体を一度に計算します。
71 引数:
72 :param x: 計算対象の入力配列
73 :type x: numpy.ndarray
74 戻り値:
75 :returns: 計算結果が格納された新しい配列
76 :rtype: numpy.ndarray
77 """
78 # Multiple compiled ufunc calls; temporary arrays are created.
79 return np.sin(x) + x*x + 1.0
80
81
82# Convenience wrapper: this still calls Python once per element.
83numpy_vectorize = np.vectorize(scalar_function, otypes=[np.float64])
84
85
86def numba_loop_source(x):
87 """
88 概要:
89 NumbaのJITコンパイル対象となるループ計算関数のソースです。
90 引数:
91 :param x: 計算対象の入力配列
92 :type x: numpy.ndarray
93 戻り値:
94 :returns: 計算結果が格納された新しい配列
95 :rtype: numpy.ndarray
96 """
97 out = np.empty_like(x)
98 for i in range(x.size):
99 out[i] = math.sin(x[i]) + x[i]*x[i] + 1.0
100 return out
101
102
103def main():
104 """
105 概要:
106 ベンチマークのメイン処理を実行します。
107 詳細説明:
108 コマンドライン引数をパースし、指定された回数だけ各手法による計算を繰り返し実行します。
109 Numbaがインストールされている場合は、Numbaを用いた手法も比較対象に加えます。
110 ウォームアップ実行による検証を行い、トライアル実行の処理時間を中央値等で表示します。
111 例外:
112 :raises AssertionError: 検証で計算結果が基準値と一致しない場合に発生します。
113 """
114 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
115 parser.add_argument('-n', '--count', type=int, default=1_000_000)
116 parser.add_argument('--repeat', type=int, default=5)
117 parser.add_argument('--no-numba', action='store_true')
118 args = parser.parse_args()
119 if args.count < 1 or args.repeat < 1:
120 parser.error('count and repeat must be positive')
121 x = np.linspace(-3.0, 3.0, args.count, dtype=np.float64)
122 reference = numpy_ufunc(x)
123 methods = [('Python for', python_loop), ('list comprehension', python_listcomp),
124 ('NumPy ufunc', numpy_ufunc), ('np.vectorize', numpy_vectorize)]
125 startup = {}
126 print(f'Python {platform.python_version()}, NumPy {np.__version__}, {platform.system()}')
127 print(f'f(x)=sin(x)+x*x+1; float64; n={args.count:,}; repeat={args.repeat}')
128 print('Numba: CPU, serial, fastmath=False, cache=False', flush=True)
129 if not args.no_numba:
130 try:
131 import numba
132 except ImportError as exc:
133 print(f'Numba skipped: {exc} (install: python -m pip install numba)')
134 else:
135 print(f'Numba {numba.__version__}')
136 # No explicit signatures: compilation is deferred until first use.
137 # Time decorator creation + first call together for each method.
138 t0 = perf_counter()
139 jit_ufunc = numba.vectorize(target='cpu', cache=False)(scalar_function)
140 jit_ufunc(x[:1])
141 startup['Numba @vectorize'] = perf_counter()-t0
142 t0 = perf_counter()
143 jit_loop = numba.njit(cache=False, fastmath=False)(numba_loop_source)
144 jit_loop(x[:1])
145 startup['Numba @njit'] = perf_counter()-t0
146 methods += [('Numba @vectorize', jit_ufunc), ('Numba @njit', jit_loop)]
147 # Exercise the full input before measuring any trials.
148 # For Numba this follows the one-element compilation warmup above.
149 for name, func in methods:
150 t0 = perf_counter()
151 y = func(x)
152 startup[name] = startup.get(name, 0.0) + perf_counter()-t0
153 if not np.all(np.isfinite(y)) or not np.allclose(y, reference, rtol=1e-12, atol=1e-12):
154 raise AssertionError(f'{name}: warmup result mismatch')
155 del y
156 print('\nStartup/warmup (separate from trials; Numba includes JIT):')
157 for name, _ in methods:
158 print(f' {name:20s} {startup[name]:.6f} s')
159 times = {name: [] for name, _ in methods}
160 errors = {name: 0.0 for name, _ in methods}
161 # Rotate execution order across trials to reduce fixed-order bias.
162 for trial in range(args.repeat):
163 offset = trial % len(methods)
164 for name, func in methods[offset:] + methods[:offset]:
165 t0 = perf_counter()
166 y = func(x)
167 elapsed = perf_counter()-t0
168 times[name].append(elapsed)
169 if not np.all(np.isfinite(y)) or not np.allclose(y, reference, rtol=1e-12, atol=1e-12):
170 raise AssertionError(f'{name}: trial {trial+1} mismatch')
171 errors[name] = max(errors[name], float(np.max(np.abs(y-reference))))
172 del y
173 print(f'Trial {trial+1}/{args.repeat} complete', flush=True)
174 base = median(times[methods[0][0]])
175 print('\nmethod median(s) minimum(s) speedup max.abs.err match')
176 for name, _ in methods:
177 med = median(times[name])
178 ratio = base/med if med else float('inf')
179 print(f'{name:22s} {med:11.6f} {min(times[name]):12.6f} {ratio:9.2f}x {errors[name]:14.3e} True')
180 print('\nnp.vectorize is a convenience wrapper, not compilation.')
181 print('NumPy expression uses multiple passes; Numba can fuse this expression into one loop.')
182 print('Speedups compare these implementations, including allocation, on this machine.')
183
184
185if __name__ == '__main__':
186 main()