Numba 基本示例比纯 python 慢

Numba basic example slower than pure python

我正在尝试使用基本示例比较 numba 和 pure 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 秒

needs to compile your function based on the types of the arguments, you can either do that when defining the function by providing a signature (eager compilation) 或者你可以让 numba 在你第一次调用函数时为你推断类型(毕竟它被称为 just-in-time [JIT] 编译 :-))。 =17=]

您没有指定任何签名,所以它会在您第一次调用函数时推断并编译它。他们 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

最后使用的命令 IPythons %timeit command.