[Tutor] timeit at the command line

Kent Johnson kent37 at tds.net
Tue Oct 3 12:05:50 CEST 2006


Dick Moores wrote:
> I DID have setup code, the "x=0".  I now notice that if the "x=0" is 
> not stated as the setup code, the time difference is enormous, 
> 132-to-1 in this case.
> 
> python -m timeit  -s"x=0" "while x<100:" "  x+=1"
> 10000000 loops, best of 3: 0.116 usec per loop
> 
> python -m timeit "x=0" "while x<100:" "  x+=1"
> 100000 loops, best of 3: 15.3 usec per loop

timeit runs the setup code once, then runs the timed code many times 
with the timer running. If "x=0" is outside the loop, then the while 
loop only runs once, because x == 100 after the first time through the 
loop. So your first version is effectively timing this:

setup:
x=100

timed code:
while x<100:
   x+=1

which is of course a lot faster than actually running the loopp 100 times.

Kent



More information about the Tutor mailing list