Numba 没有按预期提高性能

Numba does not increase performance as expected

我煞费苦心地将代码中的一些函数从非 Numba 翻译成 Numba。我这样做是为了节省时间,因为我正在编写一个四叉树来计算一组相交圆的面积。但是,我没有提高效率。相反,当我取消注释 jit 装饰器时,效率 下降 !整个代码在没有装饰器的情况下大约需要 1 秒,使用装饰器大约需要 3 秒。我在另一个包含无法转换为 Numba 格式的对象的循环中重复调用两个 Numba 函数。

整段代码有数百行长,因此我将提供一个最小的示例来说明我的算法中的一个关键操作(比较 Numpy 数组中的元素)。 Python 版本为 2.7.15,numba 版本为 0.41.0+0.gf118cda06.dirty

import numpy  as     np
import numba
from datetime import datetime
from numba    import jit  

@jit(nopython=True)
def test():
    a = np.array([0.3, 0.5])
    b = np.array([0.4, 0.6])
    c = (a[0] < b[1])
    return c
start = datetime.now()
c     = test()
end   = datetime.now()
diff  = end - start 
print "c is", c, diff.microseconds, "microseconds"

@jit(nopython=True) 装饰器 未注释 (如代码片段中所示)时,我得到:

c is True 0 microseconds

当它被评论时,我得到:

c is True 153000 microseconds

为什么这么不利?

numba.jit 被称为 jit 因为它是 JIT。如 just-in-time 编译。 It doesn't compile anything until the first call to the function. 你在计算编译成本。

通过 telling it what signatures to expect 可以使 Numba 编译函数 ahead-of-time,但这样做没有什么好处。

此外,diff.microseconds 只是微秒部分,省略了秒或天。您需要 diff.total_seconds(),它给出一个浮点数,表示以秒为单位的 timedelta 的总持续时间,或者 diff / timedelta(microseconds=1) 表示一个以微秒为单位的值。