Numba slows down my program instead of speeding it up

一笑奈何 提交于 2019-12-11 14:03:31

问题


I came across a piece of code which did the job I wanted it to do a lot quicker than my original code did. However, unlike my original code this one is slowed down by the numba jit function instead of sped up. Does anyone have an idea of why this is? This is the code without numba:

def sum_factors(n):  
    result = []
    for i in range(1, int(n**0.5) + 1):
        if n % i == 0:
            result.extend([i, n//i])
    return sum(set(result)-set([n]))

def amicable_pair(number):
    result = []
    for x in range(1,number+1):
        y = sum_factors(x)
        if sum_factors(y) == x and x != y:
            result.append(tuple(sorted((x,y))))
    return set(result)
print(amicable_pair(100000))

And this is the code with the numba function:

from numba import jit
@jit
def sum_factors(n):  
    result = []
    for i in range(1, int(n**0.5) + 1):
        if n % i == 0:
            result.extend([i, n//i])
    return sum(set(result)-set([n]))
@jit
def amicable_pair(number):
    result = []
    for x in range(1,number+1):
        y = sum_factors(x)
        if sum_factors(y) == x and x != y:
            result.append(tuple(sorted((x,y))))
    return set(result)
print(amicable_pair(100000))

The first code takes 1.7 seconds to run in a jupyter notebook and the second code takes 6.5 seconds also in a jupyter notebook.


回答1:


You have to adopt your code for jit-compiling:

@numba.njit
def sum_factors(n):  
    result = 1
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            result += i + n//i
    return result

def amicable_pair(number):
    result = []
    for x in range(1,number+1):
        y = sum_factors(x)
        if sum_factors(y) == x and x != y:
            result.append(tuple(sorted((x,y))))
    return set(result)
print(amicable_pair(100000))


来源:https://stackoverflow.com/questions/48988579/numba-slows-down-my-program-instead-of-speeding-it-up

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!