[Tutor] timeit at the command line

Dick Moores rdm at rcblue.com
Tue Oct 3 14:31:39 CEST 2006

At 04:35 AM 10/3/2006, Kent Johnson wrote:
>Dick Moores wrote:
> > At 03:05 AM 10/3/2006, Kent Johnson wrote:
> >> 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.
> >
> > Thanks, Kent. I was beginning to understand this, and now you've
> > nailed it down for me.
>You might want to look at the source, timeit.py. There is a code
>template (called 'template') near the beginning. Your setup and timed
>code are inserted into the template, then it is compiled and run.

Very interesting. I thought a line of that template looked familiar. 
I was seeing "_t0 = _timer()" regularly when I had the -s option set 
without any setup:

C:\>python -m timeit  -r 3 -s"for x in range(10000):" " x*x"
Traceback (most recent call last):
   File "E:\Python25\lib\runpy.py", line 95, in run_module
     filename, loader, alter_sys)
   File "E:\Python25\lib\runpy.py", line 52, in _run_module_co
     mod_name, mod_fname, mod_loader)
   File "E:\Python25\lib\runpy.py", line 32, in _run_code
     exec code in run_globals
   File "E:\Python25\lib\timeit.py", line 285, in <module>
   File "E:\Python25\lib\timeit.py", line 249, in main
     t = Timer(stmt, setup, timer)
   File "E:\Python25\lib\timeit.py", line 116, in __init__
     code = compile(src, dummy_src_name, "exec")
   File "<timeit-src>", line 4
     _t0 = _timer()
But I don't understand what the error has to do with _t0 . That's OK, 
don't bother to explain. I don't understand classes yet anyway. 
Should get into them soon, with Wes Chun's book.

>One of the dangers of timeit is that you may time something different
>than what you think you are timing, as you did. It's an easy mistake to
>make and hard to protect against.

Yes. thanks, Kent.


>Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list