numba@jit比纯python慢?

2024-05-23 18:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我需要改进我一直在工作的脚本的执行时间。我开始与numbajit decorator一起尝试并行计算,但它却让我感到困惑

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

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

^{pr2}$

10000个环路,最好每环路3:137µs 最慢的跑步比最快的要长7.13倍。这可能意味着正在缓存中间结果 1000000个环路,最多3个:每个环路1.75µs


Tags: 功能脚本supportparallel时间not情况decorator
1条回答
网友
1楼 · 发布于 2024-05-23 18:50:30

你不能指望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

^{pr2}$

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

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

相关问题 更多 >