Numba 基本示例比纯 python 慢

msg*_*sgb 2 python optimization numba

我正在尝试使用基本示例比较 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
Run Code Online (Sandbox Code Playgroud)

这是我用 numba 得到的时间 0.0469660758972 秒

没有 numba 我得到了更快的结果 9.60826873779e-05 秒

MSe*_*ert 5

需要根据参数的类型编译您的函数,您可以在定义函数时通过提供签名(热切编译)来执行此操作,也可以让 numba 在您第一次调用函数时为您推断类型(毕竟它被称为即时 [JIT] 编译 :-))。

您尚未指定任何签名,因此它会在您首次调用该函数时推断并编译该函数。他们甚至声明在您使用的示例中:

# jit decorator tells Numba to compile this function.
# The argument types will be inferred by Numba when function is called.
Run Code Online (Sandbox Code Playgroud)

但是后续运行(具有相同的类型和 dtypes)将很快:

t = time()
print(sum2d(a))    # 0.035051584243774414
print(time() - t)

%timeit sum2d(a)   # 1000000 loops, best of 3: 1.57 µs per loop
Run Code Online (Sandbox Code Playgroud)

最后一个命令使用了IPythons %timeitcommand