我不明白为什么 numba 在这里击败 numpy(超过 3 倍)。我在这里进行基准测试时是否犯了一些基本错误?似乎是 numpy 的完美情况,不是吗?请注意,作为检查,我还运行了一个结合 numba 和 numpy 的变体(未显示),正如预期的那样,它与在没有 numba 的情况下运行 numpy 相同。
(顺便说一句,这是一个后续问题:Fastest way to numericly process 2d-array: dataframe vs series vs array vs numba)
import numpy as np
from numba import jit
nobs = 10000
def proc_numpy(x,y,z):
x = x*2 - ( y * 55 ) # these 4 lines represent use cases
y = x + y*2 # where the processing time is mostly
z = x + y + 99 # a function of, say, 50 to 200 lines
z = z * ( z - .88 ) # of fairly simple numerical operations
return z
@jit
def proc_numba(xx,yy,zz):
for j in range(nobs): # as pointed out by Llopis, this for loop
x, y = xx[j], yy[j] # is not needed here. it is here by
# accident because in the original benchmarks
x = x*2 - ( y * 55 ) # I was doing data creation inside the function
y = x + y*2 # instead of passing it in as an array
z = x + y + 99 # in any case, this redundant code seems to
z = z * ( z - .88 ) # have something to do with the code running
# faster. without the redundant code, the
zz[j] = z # numba and numpy functions are exactly the same.
return zz
x = np.random.randn(nobs)
y = np.random.randn(nobs)
z = np.zeros(nobs)
res_numpy = proc_numpy(x,y,z)
z = np.zeros(nobs)
res_numba = proc_numba(x,y,z)
结果:
In [356]: np.all( res_numpy == res_numba )
Out[356]: True
In [357]: %timeit proc_numpy(x,y,z)
10000 loops, best of 3: 105 µs per loop
In [358]: %timeit proc_numba(x,y,z)
10000 loops, best of 3: 28.6 µs per loop
我在 2012 macbook air (13.3) 标准 anaconda 发行版上运行它。如果相关,我可以提供有关我的设置的更多详细信息。