[Tutor] timeit at the command line

Kent Johnson kent37 at tds.net
Tue Oct 3 16:08:07 CEST 2006

Dick Moores wrote:
> At 05:54 AM 10/3/2006, Kent Johnson wrote:
>> Dick Moores wrote:
>>> 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>
>>>      sys.exit(main())
>>>    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.
>> If you substitute your code into the template by hand and look at 
>> the actual exception (not shown above) you should see the problem. 
>> It doesn't have anything to do with classes.
> I meant timeit.py has classes.
> OK, I called timeit.py with this template:
> template = """
> def inner(_it, _timer):
>      %(setup)s
>      _t0 = _timer()
>      for _i in _it:
>          %("x=0" "while x<100": " x*x")s
>      _t1 = _timer()
>      return _t1 - _t0
> """

OK, let's go back to your first example and I will explain in more detail.

timeit.py contains this template:
template = """
def inner(_it, _timer):
     _t0 = _timer()
     for _i in _it:
     _t1 = _timer()
     return _t1 - _t0

Whatever you specify for setup code is substituted for %(setup)s; the 
timed statement is substituted for %(stmt)s. This is done using standard 
string formatting operations. The result of the substitutions is a 
function definition which is compiled and run.

So if you run
python -m timeit -s"for x in range(10000):" " x*x"

the generated function looks like this:
def inner(_it, _timer):
     for x in range(10000):
     _t0 = _timer()
     for _i in _it:
     _t1 = _timer()
     return _t1 - _t0

The for statement should begin an indented block; the next statement is 
*not* indented, so you get an IndentationError.

Does that help?

More information about the Tutor mailing list