麻木慢语?

2024-05-26 07:46:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我对使用numba获得的HERE加速效果印象深刻

今天我在soa 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)

结果是:

^{pr2}$

为什么会这样?似乎有了numba这段代码并没有变得更快!在


Tags: to代码infromnewtimestartprime
1条回答
网友
1楼 · 发布于 2024-05-26 07:46:55

这是您的代码的一个麻木版本(使用numba0.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()

然后与时间进行比较:

^{pr2}$

这是20倍的加速,尽管可能还有进一步的优化。如果没有jit decorator,numba版本在我的机器上运行大约300毫秒。对primes_util的实际调用只需大约5毫秒,其余的是对np.nonzero的调用和对列表的转换。在

相关问题 更多 >