I was under the impression that using a sum construction was much faster than running a for loop. However, in the following code, the for loop actually runs faster:
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)
The output is:
208
208
Version 1 time: 0.9300529956817627
Version 2 time: 1.066061019897461
Am I doing something wrong? Is there a way to do this faster?
(Note that this is just a demo I set up, in my real application the scores will not be repeated in this manner)
Some additional info: This is run on Python 3.4.4 64-bit, on Windows 7 64-bit, on an i7.