我刚刚注意到,通过仅将乘法变为除法,我的脚本的执行时间几乎减半.
为了研究这个,我写了一个小例子:
import numpy as np
import timeit
# uint8 array
arr1 = np.random.randint(0, high=256, size=(100, 100), dtype=np.uint8)
# float32 array
arr2 = np.random.rand(100, 100).astype(np.float32)
arr2 *= 255.0
def arrmult(a):
"""
mult, read-write iterator
"""
b = a.copy()
for item in np.nditer(b, op_flags=["readwrite"]):
item[...] = (item + 5) * 0.5
def arrmult2(a):
"""
mult, index iterator
"""
b = a.copy()
for i, j in np.ndindex(b.shape):
b[i, j] = (b[i, j] + 5) * 0.5
def arrmult3(a):
"""
mult, vectorized
""" …Run Code Online (Sandbox Code Playgroud) 我注意到,非常紧张,np.sum比手写总和慢10倍.
带轴的np.sum:
p1 = np.random.rand(10000, 2)
def test(p1):
return p1.sum(axis=1)
%timeit test(p1)
Run Code Online (Sandbox Code Playgroud)
每回路186μs±4.21μs(平均值±标准偏差,7次运行,每次1000次循环)
没有轴的np.sum:
p1 = np.random.rand(10000, 2)
def test(p1):
return p1.sum()
%timeit test(p1)
Run Code Online (Sandbox Code Playgroud)
每回路17.9μs±236 ns(平均值±标准偏差,7次运行,每次10000次循环)
+:
p1 = np.random.rand(10000, 2)
def test(p1):
return p1[:,0] + p1[:,1]
%timeit test(p1)
Run Code Online (Sandbox Code Playgroud)
每个环路15.8μs±328 ns(平均值±标准偏差,7次运行,每次100000次循环)
乘法:
p1 = np.random.rand(10000, 2)
def test(p1):
return p1[:,0]*p1[:,1]
%timeit test(p1)
Run Code Online (Sandbox Code Playgroud)
每个环路15.7μs±701 ns(平均值±标准偏差,7次运行,每次10000次循环)
我没有看到任何理由.知道为什么吗?我的numpy版本是1.15.3.
编辑:10000000:
np.sum (with axis): 202 ms (5 x)
np.sum (without axis): 12 ms
+ : 46 ms (1 x)
* : 44.3 ms …Run Code Online (Sandbox Code Playgroud)