Skip to main content
 首页 » 编程设计

python之有没有办法估计循环本身的 Python 解释器开销

2024年11月01日8小虾米

这post说

if the body of your loop is simple, the interpreter overhead of the loop itself can be a substantial amount of the overhead

并给出这个 example来说明并行。

def convolve_random(size): 
    ''' Convolve two random arrays of length "size" ''' 
    return np.convolve(np.random.random_sample(size), np.random.random_sample(size)) 
%timeit convolve_random(40000) 
1 loops, best of 3: 904 ms per loop 
 
%timeit [convolve_random(40000 + i*1000) for i in xrange(8)] 
# In parallel, with 8 jobs 
%timeit Parallel(n_jobs=8)(delayed(convolve_random)(40000 + i*1000) for i in xrange(8)) 
1 loops, best of 3: 8.69 s per loop 
1 loops, best of 3: 2.88 s per loop 

在这种情况下,有没有办法估计循环本身的 Python 解释器开销?

请您参考如下方法:

Q : is there a way to estimate the Python interpreter overhead of the loop itself?

您已经收到answer 3 hours ago为此,使用 [us]-resolution timings 提供基准测试模板的说明。

如果您没有尝试 recommended测试 templates要对其进行测量,请继续进行,您将收到硬数据,循环成本是多少(最好使用超出缓存大小的数据样本 + 避免生成 np.random.random() 的成本)。