
2.3
NumPy
配列の計算:ユニバーサル関数
51
In[1]: import numpy as np
np.random.seed(0)
def compute_reciprocals(values):
output = np.empty(len(values))
for i in range(len(values)):
output[i] = 1.0 / values[i]
return output
values = np.random.randint(1, 10, size=5)
compute_reciprocals(values)
Out[1]: array([ 0.16666667, 1. , 0.25 , 0.25
, 0.125 ])
この実装は、おそらく
C
言語や
Java
の経験を持つ人には自然な感じがするはずです。しかし、
大きな入力に対するこのコードの実行時間を測定すると、この操作は驚くほど遅いことがわかり
ます。これを(「1.9 コードのプロファイリングと実行時間計測」で説明した)
IPython
の
%timeit
Magic
コマンドを使ってベンチマークします。
In[2]: big_array = np.random.randint(1, 100, size=1000000)
%timeit compute_reciprocals(big_array)
1 loop, best of 3: 2.91 s per loop
100
万回の計算を行い、結果を保存するには数秒