有没有办法比使用for循环更快地总结一个数字列表,可能在Python库中?或者只是多线程/矢量处理才能有效地完成?
编辑:只是为了澄清,它可以是任何数字的列表,未分类,只是来自用户的输入.
我想看看比使用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
Run Code Online (Sandbox Code Playgroud)
再看一点:
In [68]: timeit("1+2", setup)
Out[68]: 0.04145693778991699
In [69]: timeit("add(1,2)", setup)
Out[69]: 0.22807812690734863
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?显然,reduce会比for循环更快,但函数调用似乎占主导地位.减少版本不应该几乎完全在C中运行吗?在for循环版本中使用iadd(c,i)使其在~24秒内运行.为什么使用operator.add比+慢得多?我的印象是+和operator.add运行相同的C代码(我检查以确保operator.add不只是在python中调用+或任何东西).
顺便说一句,只需在~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)]
Run Code Online (Sandbox Code Playgroud)