[Tutor] timeit at the command line

Dick Moores rdm at rcblue.com
Tue Oct 3 15:47:32 CEST 2006

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):
     _t0 = _timer()
     for _i in _it:
         %("x=0" "while x<100": " x*x")s
     _t1 = _timer()
     return _t1 - _t0
And got this error:

Traceback (most recent call last):
   File "E:\Python25\Scripts-NotMine\timeit.py", li
   File "E:\Python25\Scripts-NotMine\timeit.py", li
     t = Timer(stmt, setup, timer)
   File "E:\Python25\Scripts-NotMine\timeit.py", li
     src = template % {'stmt': stmt, 'setup': setup
KeyError: '"x=0" "while x<100": " x*x"'

So what's the error? I've probably misunderstood how to do the substitution..


More information about the Tutor mailing list