【问题标题】:numba @jit slower that pure python?numba @jit 比纯 python 慢吗?
【发布时间】:2017-12-22 16:08:11
【问题描述】:

所以我需要改进我一直在处理的脚本的执行时间。我开始使用 numba jit 装饰器来尝试并行计算,但是它让我失望了

KeyError: "Does not support option: 'parallel'"

所以我决定测试 nogil,如果它从我的 cpu 解锁全部功能,但它比纯 python 慢我不明白为什么会发生这种情况,如果有人可以帮助我或指导我,我将非常感激

import numpy as np
from numba import *
@jit(['float64[:,:],float64[:,:]'],'(n,m),(n,m)->(n,m)',nogil=True)
def asd(x,y):
    return x+y
u=np.random.random(100)
w=np.random.random(100)

%timeit asd(u,w)
%timeit u+w

10000 次循环,3 次中的最佳:每个循环 137 µs 最慢的运行时间比最快的运行时间长 7.13 倍。这可能意味着正在缓存中间结果 1000000 次循环,3 次中的最佳:每个循环 1.75 µs

【问题讨论】:

    标签: python parallel-processing jit numba


    【解决方案1】:

    你不能指望 numba 在这样一个简单的向量化操作上胜过 numpy。此外,您的比较也不完全公平,因为 numba 函数包括外部函数调用的成本。如果你对一个更大的数组求和,你会看到两者的性能收敛,而你看到的只是一个非常快速的操作的开销:

    import numpy as np
    import numba as nb
    
    @nb.njit
    def asd(x,y):
        return x+y
    
    def asd2(x, y):
        return x + y
    
    u=np.random.random(10000)
    w=np.random.random(10000)
    
    %timeit asd(u,w)
    %timeit asd2(u,w)
    
    The slowest run took 17796.43 times longer than the fastest. This could mean 
    that an intermediate result is being cached.
    100000 loops, best of 3: 6.06 µs per loop
    
    The slowest run took 29.94 times longer than the fastest. This could mean that 
    an intermediate result is being cached.
    100000 loops, best of 3: 5.11 µs per loop
    

    就并行功能而言,对于这个简单的操作,您可以使用nb.vectorize

    @nb.vectorize([nb.float64(nb.float64, nb.float64)], target='parallel')
    def asd3(x, y):
        return x + y
    
    u=np.random.random((100000, 10))
    w=np.random.random((100000, 10))
    
    %timeit asd(u,w)
    %timeit asd2(u,w)
    %timeit asd3(u,w)
    

    但同样,如果您对小型数组进行操作,您将看到线程调度的开销。对于上面的数组大小,我看到并行给了我 2 倍的加速。

    numba 真正闪耀的地方是使用广播在 numpy 中难以执行的操作,或者当操作会导致大量临时中间数组分配时。

    【讨论】:

    • 嗨@JoshAdel,谢谢你的回答,我的真实代码是一个优化算法,所以它必须迭代相同的函数并检查改进,所以我不知道参数值的不断变化和如果我对执行次数最多的函数进行矢量化,嵌套函数的数量将是一个问题。再次感谢您
    猜你喜欢
    • 2020-02-29
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2017-06-07
    • 2015-02-12
    • 1970-01-01
    相关资源
    最近更新 更多