Numba 不会加速 "speed up your code using numba" 在线示例中的代码

Numba does not speed up code found in "speed up your code using numba" examples online

我决定开始使用 Numba to speed up some scientific code I have. To get my feet wet, I googled and found some tutorials that provide runtimes. The tutorial example I'm referring to comes from here。他们从 numpy 数组计算标准偏差,然后使用 Numba 的 @njit 装饰器再次计算,然后他们比较 运行 次。这是我在我的计算机上重新创建此代码的尝试:

import math
import numpy as np
import numba
from timeit import timeit

def std(xs):
    # compute the mean
    mean = 0
    for x in xs:
        mean += x
    mean /= len(xs)
    # compute the variance
    ms = 0
    for x in xs:
        ms += (x - mean) ** 2
    variance = ms / len(xs)
    std = math.sqrt(variance)
    return std

c_std = numba.njit(std)

a = np.random.normal(0, 1, 10000)

现在这是我在时间方面得到的:

print(timeit('std(a)', globals=globals(), number=1) * 1000, 'ms')

运行 9 毫秒。但是,当我合并 Numba 时:

print(timeit('c_std(a)', globals=globals(), number=1) * 1000, 'ms')

运行秒,375 毫秒。

减速 大约 40 倍。在教程中,使用相同的代码,他们的 Numba-jitted 代码 运行s 在 31.6 毫秒内,与没有 Numba 的 4600 毫秒相比,加速了大约 150 倍。我能看到的我们的代码之间的唯一区别是它们的正态分布样本来自 10,000,000 个点,而我的只有 10,000 个,但这是必要的调整,因为 运行 个点花费的时间太长了。

我在 Python 3.8 上使用 Numpy 1.19.2 和 Numba 0.51.2。我在 MacOs 10.14 上 运行ning conda 4.9.2。

感谢 Monica 的评论指出我在计时编译。当我 运行 c_std 一次 before 计时时,这是固定的:

# Run once to compile~!
std(a)
c_std(a)

time_a = timeit('std(a)', globals=globals(), number=1) * 1000
print(f'No numba: {time_a:.3f} ms')

time_b = timeit('c_std(a)', globals=globals(), number=1) * 1000
print(f'Yes numba: {time_b:.3f} ms')

returns:

无 numba:9.024 毫秒

是 numba:0.025 毫秒