python - Numba 减慢代码?

标签 python performance numba

所获得的加速给我留下了深刻的印象HERE通过使用numba

今天我在SO中发现了一个question来自希望加速其代码的人。所以我想让我们看看我们可以使用 numba 实现什么。

代码如下:

from numba import autojit
from time import time

LIMIT = pow(10,6)

def primes(limit):
    # Keep only odd numbers in sieve, mapping from index to number is
    # num = 2 * idx + 3
    # The square of the number corresponding to idx then corresponds to:
    # idx2 = 2*idx*idx + 6*idx + 3
    sieve = [True] * (limit // 2)
    prime_numbers = set([2])
    for j in range(len(sieve)):
        if sieve[j]:
            new_prime = 2*j + 3
            prime_numbers.add(new_prime)
            for k in range((2*j+6)*j+3, len(sieve), new_prime):
                sieve[k] = False
    return list(prime_numbers)


numba_primes = autojit(primes)



start = time()
numba_primes(LIMIT)
end=time()
print("Numba: Time Taken : ",end-start)

start = time()
primes(LIMIT)
end=time()
print("Python: Time Taken : ",end-start)

结果:

('Numba: Time Taken : ', 0.68790602684021)
('Python: Time Taken : ', 0.12417221069335938)

为什么会发生这种情况?看来使用 numba 这段代码并没有变得更快!

最佳答案

这是代码的 numba 化版本(使用 Numba 0.13),这是通过使用 numpy 数组进行优化的

import numpy as np
import numba

# You could also just use @numba.jit or @numba.jit(nopython=True)
# here and get comparable timings.
@numba.jit('void(uint8[:])', nopython=True)
def primes_util(sieve):
    ssz = sieve.shape[0]
    for j in xrange(ssz):
        if sieve[j]:
            new_prime = 2*j + 3
            for k in xrange((2*j+6)*j+3, ssz, new_prime):
                sieve[k] = False

def primes_numba(limit):
    sieve = np.ones(limit // 2, dtype=np.uint8)
    primes_util(sieve)

    return [2] + (np.nonzero(sieve)[0]*2 + 3).tolist()

然后与时间进行比较:

In [112]: %timeit primes(LIMIT)
1 loops, best of 3: 221 ms per loop

In [113]: %timeit primes_numba(LIMIT)
100 loops, best of 3: 11 ms per loop

In [114]:

a = set(primes(LIMIT))
b = set(primes_numba(LIMIT))

a == b
Out[114]:

True

尽管可能还可以进行进一步的优化,但速度提升了 20 倍。如果没有 jit 装饰器,numba 版本在我的机器上运行大约需要 300 毫秒。对 primes_util 的实际调用只需要大约 5 毫秒,剩下的就是对 np.nonzero 的调用以及对列表的转换。

关于python - Numba 减慢代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22768709/

相关文章:

Python:跨线程共享类变量

python从xml中读取数据

python - 当 python 类 jitclass 包含自身 jitclass 类时,如何使其兼容?

python - 如何将附加参数传递给 numba cfunc 作为 LowLevelCallable 传递给 scipy.integrate.quad

python - 使用内联其他函数编译带有函数的 Numba 模块时出错

python - 使用 Anaconda 安装 github 版本的包

python - 如何随机化画板中显示的图像

performance - 训练某些网络时,Keras(Tensorflow 后端)在 GPU 上比在 CPU 上慢

c++ - 根据 valgrind,malloc 和 new 在整体成本中占有巨大份额。我怎样才能减少它?

javascript - 在菜单类型代码中,循环先于条件或条件先于循环哪个更好?