2017-02-10 45 views
2

我试图比较使用基本示例的numba和纯python,并且得到了奇怪的结果。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 

这是我得到与numba0.0469660758972秒

而且没有numba时机我得到更快的结果9.60826873779e-05秒

+0

这是一个非常小的例子。你如何计时? –

+0

@terencehill感谢您的快速回复。我编辑了我的原始文章 – msgb

+1

您可能花费大部分时间编译 – user357269

回答

3

需要根据参数的类型来编译您的函数,您可以通过提供签名(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. 

但是后续运行(与同类型和dtypes)将是快速:

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

+0

TLDR;需要注意的是使用魔法单元格'%% timeit'来再次运行单元格,并在每次调用时都让numba推断出类型。对函数进行预调用使用行魔法单元格'%timeit'更好 – MCMZL