我的印象是使用总和构造比运行for循环要快得多。然而,在下面的代码中,for循环实际运行速度更快:Python中“总和”理解的速度
import time
Score = [[3,4,5,6,7,8] for i in range(40)]
a=[0,1,2,3,4,5,4,5,2,1,3,0,5,1,0,3,4,2,2,4,4,5,1,2,5,4,3,2,0,1,1,0,2,0,0,0,1,3,2,1]
def ver1():
for i in range(100000):
total = 0
for j in range(40):
total+=Score[j][a[j]]
print (total)
def ver2():
for i in range(100000):
total = sum(Score[j][a[j]] for j in range(40))
print (total)
t0 = time.time()
ver1()
t1 = time.time()
ver2()
t2 = time.time()
print("Version 1 time: ", t1-t0)
print("Version 2 time: ", t2-t1)
输出是:
208
208
Version 1 time: 0.9300529956817627
Version 2 time: 1.066061019897461
难道我做错了什么?有没有办法做得更快?
(请注意,这只是一个演示中,我设置了,在我的实际应用中的成绩将不会以这种方式重复)
一些附加信息:这是关于Python 3.4.4 64位运行,在Windows 7 64位上,在i7上。
[this question](http:// stackoverflow。com/questions/24578896/python-built-in-sum-function-vs-for-loop-performance)说'sum'应该比'for'循环快得多。 – Barmar
我认为你的瓶颈是列表理解,而不是加法。 – Barmar
@Barmar在这两个函数中都没有列表理解。为什么一个*生成器理解*是一个瓶颈,因为它和for循环完全相同?我认为这可能只是函数调用'sum'的开销,因为范围非常小... – L3viathan