timeit module: am I missing something obvious?

Steven D'Aprano steve at REMOVEMEcyber.com.au
Mon Feb 20 02:53:55 EST 2006


When using the timeit module, you pass the code you 
want to time as strings:

import timeit
t = timeit.Timer("foo(x, y)", \
"""from module import foo
x = 27
y = 45
""")
elapsed_time = t.timeit()

This is all very well, but it feels quite unnatural to 
me. Why am I passing strings around when functions are 
first class objects? Have I missed something obvious?

I understand that sometimes you have to pass strings, 
because statements are NOT objects in Python. But what 
about when your code doesn't use statements?

It seems to me it would be really useful to be able to 
do something like this:

# this doesn't work...
import timeit
from module import foo
x = 27
y = 45
t = timeit.Timer(foo, args=[x, y])
elapsed_time = t.timeit()

instead of messing about with setup strings and the like.

Am I missing something obvious? Does this functionality 
already exist? Is there a reason why it can't exist?



-- 
Steven.




More information about the Python-list mailing list