【问题标题】:Execution Time Difference based on sum() on IPython基于 IPython 上 sum() 的执行时间差
【发布时间】:2013-08-29 20:50:21
【问题描述】:

我正在使用 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 倍。这可能是什么原因?

【问题讨论】:

    标签: python ipython ipython-parallel


    【解决方案1】:

    我不能太深入,但速度较慢的原因是因为sum(&lt;array&gt;) 是内置的 CPython sum 函数,而您的 &lt;numpy array&gt;.sum() 使用的是 numpy sum 函数,它比内置python版本。

    我想如果您将sum(&lt;array&gt;) 替换为numpy.sum(&lt;array&gt;),您会得到类似的结果

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

    【讨论】:

    • 谢谢@Cameron Sparr
    猜你喜欢
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多