[Tutor] What's the problem with my SpinSpeeds.py?

Kent Johnson kent_johnson at skillsoft.com
Tue Aug 3 14:58:04 CEST 2004


The timeit module is using the exec statement to run the code you give it.

Exec takes a string value and runs it as Python code. For example
 >>> exec "print 'Hello, world!'"
Hello, world!
 >>> exec "a=3; print a"
3

This is useful if you want to run user-supplied code, which is what timeit 
does.
There is a brief description of exec here: http://docs.python.org/ref/exec.html

If you are feeling brave you can look at timeit.py yourself and see what it 
does :-) (Look in the Lib directory of your Python installation.) It's use 
of exec is quite a bit more sophisticated than my examples. In your case, 
timeit actually creates a string containing this program:
def inner(_it, _timer):
     from __main__ import countUsingRange, n
     _t0 = _timer()
     for _i in _it:
         countUsingRange(n)
     _t1 = _timer()
     return _t1 - _t0

It uses exec to execute the string, which _defines_ the function inner() 
without running it. Then it extracts the function object itself from the 
exec'ed code and runs it.

HTH
Kent

At 01:31 AM 8/3/2004 -0700, Dick Moores wrote:
>Alan Gauld wrote at 11:21 8/2/2004:
>> >      t = Timer("countUsingRange(n)", "from __main__ import
>> > countUsingRange, n")
>> >      rangeTime = t.timeit(repetitions)
>>
>>This executes and times the string
>>
>>"countUsingRange(n)"
>>
>>after first executing
>>
>>"from __main__ import countUsingRange, n".
>
>Thank you for clearing up some of the mystery. The basic one for me is 
>what it means to execute a string, as in, 'This executes and times the string
>"countUsingRange(n)"'.  And why does Timer take arguments that are in 
>quotes, (which makes them strings, I suppose).  It seems that my discovery 
>of the timeit module has gotten me in over my head, IOW ahead of myself in 
>my learning of Python.
>
>Dick Moores
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list