我正在尝试计算大量的 GCD(x,y)
作为 Euler 625 的一部分由于这需要很多时间,我尝试添加 @numba jit
来加快速度。
我检查了类似的问题,如 this , this和 this但它们没有帮助(我没有使用numpy
或使用可并行函数(如sum
),并且我多次调用这些函数 - 所以编译懒惰不是'也不是问题)
结果是:
with numba: 8.220806121826172 seconds
without numba: 1.242861270904541 seconds
我的代码添加在下面。
- 为什么 numba 会减慢我的速度?
我怎样才能更快地执行这个(原来的限制是10**11,这看起来是无法计算的)
import time from numba import jit, int32 gcd_dict = {} #@jit def gcd(x, y ,k = None, reverse_k = None): if not k: k = (x,y) reverse_k = (y,x) if k in gcd_dict: return gcd_dict[k] elif reverse_k in gcd_dict: return gcd_dict[reverse_k] if not y: if len(gcd_dict) < 10**6: gcd_dict[k] = x gcd_dict[reverse_k] = x return x else: return gcd(y, x % y, k, reverse_k) def main(): t = time.time() s = 0 # i_limit = 10**11+1 i_limit = 10**3 for i in range(1,i_limit): for j in range(1,i+1): s += gcd(i,j) print(s) print(time.time() - t) main()
最佳答案
numba 不支持字典,因此它会退回到 Python 模式,从而导致运行时开销。
如果将 @jit
替换为 @jit(nopython=True)
,您会看到 JIT 编译失败,这会禁止切换到 Python,从而在如果您使用不受支持的 Python 功能。
关于python - numba jit 是否有可能减慢我的 gcd 执行速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52419402/