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

ufunc_benchmark.py をダウンロード

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