【问题标题】:Is it possible that numba jit slows down my gcd execution?numba jit 是否有可能减慢我的 gcd 执行速度?
【发布时间】:2018-09-20 07:03:03
【问题描述】:

我正在尝试计算大量 GCD(x,y) 作为 Euler 625 的一部分,由于这需要很多时间,我尝试添加 @numba jit 以加快速度。

我检查了类似的问题,如 this、this 和 this,但它们没有帮助(我没有使用 numpy 或使用可并行函数(如 sum),我调用了多次运行 - 所以编译懒惰也不是问题) 结果是:

with    numba: 8.220806121826172 seconds
without numba: 1.242861270904541 seconds

我的代码添加在下面。

  1. 为什么 numba 会减慢我的速度?
  2. 我怎样才能更快地执行这个(原来的限制是 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 减慢您速度的结论:您表明 numba 为您提供了 7 倍的加速(从 8.2 秒到 1.2 秒)。
  • 愚蠢的错误。我换了行 :-( ...正如标题所述,jitted 版本较慢

标签: python jit numba


【解决方案1】:

numba 不支持字典,因此它会退回到 Python 模式,这会导致运行时开销。

如果您将 @jit 替换为 @jit(nopython=True),您会看到 JIT 编译失败,这会禁用切换到 Python,以便在您使用不受支持的 Python 功能时收到错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    相关资源
    最近更新 更多