我尝试使用基本示例来比较 numba 和纯 python,但得到了奇怪的结果。
这是 numba 示例:
from numba import jit
from numpy import arange
from time import time
# jit decorator tells Numba to compile this function.
# The argument types will be inferred by Numba when function is called.
@jit
def sum2d(arr):
M, N = arr.shape
result = 0.0
for i in range(M):
for j in range(N):
result += arr[i,j]
return result
a = arange(9).reshape(3,3)
t = time()
print(sum2d(a))
print time() - t
这是我用 numba 得到的时间 0.0469660758972 秒
如果没有 numba,我会得到更快的结果 9.60826873779e-05 秒
最佳答案
numba需要根据参数的类型编译函数,您可以在定义函数时通过提供签名( eager compilation )来执行此操作,也可以在第一次调用函数时让 numba 为您推断类型(毕竟它被称为即时 [JIT] 编译:-))。
您尚未指定任何签名,因此它会在您第一次调用该函数时推断并编译该函数。他们even state that在您使用的示例中:
# jit decorator tells Numba to compile this function.
# The argument types will be inferred by Numba when function is called.
但是后续运行(具有相同类型和数据类型)将会很快:
t = time()
print(sum2d(a)) # 0.035051584243774414
print(time() - t)
%timeit sum2d(a) # 1000000 loops, best of 3: 1.57 µs per loop
最后一个命令使用了IPython
%timeit
command .
关于python - Numba 基本示例比纯 python 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42164886/