Numba 减慢了我的程序而不是加速 [英] Numba slows down my program instead of speeding it up

查看:54
本文介绍了Numba 减慢了我的程序而不是加速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一段代码,它完成了我希望它比我的原始代码更快地完成的工作.然而,与我的原始代码不同,这个代码被 numba jit 函数减慢而不是加速.有谁知道这是为什么?这是没有numba的代码:

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))

这是带有 numba 函数的代码:

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))

第一个代码在 jupyter notebook 中运行需要 1.7 秒,第二个代码在 jupyter notebook 中也需要 6.5 秒.

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.

推荐答案

你必须采用你的代码进行 jit 编译:

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))

这篇关于Numba 减慢了我的程序而不是加速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆