【发布时间】:2018-05-23 03:09:54
【问题描述】:
我想看看 reduce 比使用 for 循环进行简单的数值运算快多少。这是我发现的(使用标准 timeit 库):
In [54]: print(setup)
from operator import add, iadd
r = range(100)
In [55]: print(stmt1)
c = 0
for i in r:
c+=i
In [56]: timeit(stmt1, setup)
Out[56]: 8.948904991149902
In [58]: print(stmt3)
reduce(add, r)
In [59]: timeit(stmt3, setup)
Out[59]: 13.316915035247803
再看一点:
In [68]: timeit("1+2", setup)
Out[68]: 0.04145693778991699
In [69]: timeit("add(1,2)", setup)
Out[69]: 0.22807812690734863
这里发生了什么?显然,reduce 确实比 for 循环更快,但函数调用似乎占主导地位。 reduce 版本不应该几乎完全在 C 中运行吗?在 for 循环版本中使用 iadd(c,i) 使其在约 24 秒内运行。为什么使用 operator.add 会比 + 慢这么多?我的印象是 + 和 operator.add 运行相同的 C 代码(我检查以确保 operator.add 不只是在 python 中调用 + 或其他任何东西)。
顺便说一句,仅使用 sum 运行时间约为 2.3 秒。
In [70]: print(sys.version)
2.7.1 (r271:86882M, Nov 30 2010, 09:39:13)
[GCC 4.0.1 (Apple Inc. build 5494)]
【问题讨论】:
-
使用
sum的速度提高了 4 倍这一事实几乎表明“应该有一种明显的方法来做到这一点”。 -
@jsbbueno:没错,但我这样做是为了找出对序列进行一般数值计算的最快方法。在现实世界中,我肯定会使用 sum 来求和 :D 没有尝试过 mul,但我相信结果会相似。
标签: python performance