简体   繁体   中英

While loops vs for loop — speed

I have always thought that for loops run faster than while loops. However, I recently just tested the speed and cannot figure out why the while loop runs about 5 to 6 times faster. Here is the test code I wrote.

test1 = datetime.now()

ll = 100000
for kk in range(10000000):
   pass


print('Time for 100000 runs is ({}s)'.format(datetime.now() - test1))

test2 = datetime.now()

ll = 10000000
while ll > 0:
    ll = ll -11

print('Time for 100000 runs is ({}s)'.format(datetime.now() - test2))

After running this test, I get that the for loop runs in about 1.26 seconds and the while loop runs in about .22 seconds. Why do I not just always artificially turn for loops into while loops in this way if they're quicker?

Thanks!

EDIT: After people pointed out my typo, and using the suggestion @RPGillespie moving the range(10000000) out infront of the timing, I got a result matching what I expected. Namely, the for loop is about three times faster than the while loop.

This runs 10000000 or 10^7 times:

for kk in range(10000000):
   pass

This runs 10000000/11 or 909090 times, or ~9*10^5 :

ll = 10000000
while ll > 0:
    ll = ll -11

Given that they are not equivalent loops its not unexpected they run at different speeds.

I'm not a python expert so I can't attest to what datetime.now is doing (it's probably system specific) but it looks like your for loop is actually iterating more times than your while loop, which could explain the discrepancy. Change the line:

ll = ll -11

to

ll = ll -1

and you should have an equivalent number of iterations through each loop.

The following code decrements your counter by 11 rather than 1. It must be a typo?

while ll > 0:
ll = ll -11

Since your counter is decremented by a greater value in the while loop it will cause that loop to finish sooner than the for loop.

The first loop runs 10000000 times The second loop runs 909091 times

Instead try:

from datetime import datetime

test1 = datetime.now()
a = 0
b = 0
for kk in range(10000000):
   a = a + 1
print('Time for 100000 runs is ({}s)'.format(datetime.now() - test1))

test2 = datetime.now()

while b < a:
    b = b + 1
print('Time for 100000 runs is ({}s)'.format(datetime.now() - test2))

Which gives me 1.190000s and 1.061000s respectively.

The for/in idiom does generally result in faster operations. If you are concerned with speed, you should look into numpy and pypy.

The reason for the difference in speed is the way numbers generate. Expressions evaluation is faster than function calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM