问题
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