I am doing some testing regarding the speed of if-statements in loops and their effect on speed. Something I found was that consistently, the if-statement improved performance. My code:
import time
t = time.time
start = t()
x = 0
while x < 10000000:
x += 1
time1 = t()
x = 0
while x < 10000000:
x += 1
if True:
pass
time2 = t()
print(start)
print(time1 - start) # Time for simple while-loop
print(time2 - time1) # Time for while+if
A sample output would be:
1355517837.993
1.7850000858306885
1.7209999561309814
Which is completely counter-intuitive. The while-if-loop is working ever-so-slightly faster than the standard while-loop. This happens almost every time I run it; perhaps 1 in 20 times take longer. Does anyone know why?
x=0out of both timed blocks? I bet what you're seeing is the interpreter having to allocatexfor the first block but not the second.$ python t.py 1355519439.65 1.92616391182 2.65010595322; ran on Python 2.7.3time.time()is not the correct way to profile your program (since other tasks may affect the results). Usetimeit.timeit()instead.