Skip to main content
 首页 » 编程设计

python之IPython 上基于 sum() 的执行时间差

2025年05月04日10TianFang

我正在做一个简单的蒙特卡罗模拟练习,使用 IPython 的 ipcluster 引擎。根据我定义函数的方式,我注意到执行时间存在巨大差异,我正在询问原因。以下是详细信息:

当我如下定义任务时,它很快:

def sample(n): 
    return (rand(n)**2 + rand(n)**2 <= 1).sum() 

并行运行时:

from IPython.parallel import Client 
rc = Client() 
v = rc[:] 
with v.sync_imports(): 
from numpy.random import rand 
n = 1000000 
 
timeit -r 1 -n 1 print 4.* sum(v.map_sync(sample, [n]*len(v))) / (n*len(v)) 
 
3.141712 
1 loops, best of 1: 53.4 ms per loop 

但是如果我将函数更改为:

def sample(n): 
    return sum(rand(n)**2 + rand(n)**2 <= 1) 

我得到:
3.141232 1 个循环,最好的 1 个:每个循环 3.81 秒

...慢了 71 倍。这可能是什么原因?

请您参考如下方法:

我不能说得太深入,但它慢的原因是因为 sum(<array>)是内置的 CPython 求和函数,而你的 <numpy array>.sum()正在使用 numpy sum 函数,它比内置的 python 版本快得多。

我想如果你替换了 sum(<array>) 你会得到类似的结果与 numpy.sum(<array>)

请在此处查看 numpy sum 文档:http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html