Passing function objects to timeit

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Mar 29 06:33:40 EDT 2008


The timeit.Timer class times "code snippets" -- you pass it strings 
rather than function objects. That's good for what it's worth, but 
sometimes the code you want to time is too big to easily pass as a 
string, or maybe you only have access to a function object without the 
source, or for whatever reason it's not very convenient.

In this case, a good trick is to import the function by name:

timeit.Timer('spam()', 'from __main__ import spam')


But now I find myself wanting to time a function that's not defined in 
__main__. Here's a illustrative example:


def factory():
    def f():
        return "spam"
    return f

def main():
    func = factory()
    return timeit.Timer('func()', 'from __main__ import func').timeit() 


But it doesn't work:

>>> main()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in main
  File "/usr/lib/python2.5/timeit.py", line 161, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 3, in inner
ImportError: cannot import name func


Moving the definition of func into __main__ is not an option. What do I 
do? Am I reduced to re-writing the timeit module to take functions 
instead of strings? (Maybe I should do that anyway.) Or is there a way to 
inject the function object into the namespace used by timeit?



-- 
Steven



More information about the Python-list mailing list