NumPyのufuncのouterとブロードキャストの速度比較

NumPyには、outerやブロードキャストによって異なる形状の行列の演算が可能な場合がある。
試した範囲*1では必要な時間ははほぼ同じだった。

[0,1,2]という配列があった場合、
[[0,1,2],
[-1,0,1],
[-2,-1,0]]
のような
1次元配列の要素の互いの差を計算する際に、
・numpy.subtractをouterで実行した場合
・2次元配列にしてブロードキャスト
を実行した。

import numpy as np
import time as time

np.set_printoptions(suppress=True, precision=3)

N = 70000 # do not set too large number
a = np.random.rand(N) 
xx = np.zeros((N, N))

start_time = time.time()
xx = np.subtract.outer(a, a)
end_time = time.time()
print(end_time-start_time)

xx = np.zeros((N, N))
start_time = time.time()
xx = (np.atleast_2d(a) - np.atleast_2d(a).T)
end_time = time.time()
print(end_time-start_time)

実行時間[\は
N = 10000において
0.338 s
0.357 s
N = 50000において
7.156 s
7.060 s
など。
対して変わらない。

*1:非常に狭い