Passing function objects to timeit
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Sat Mar 29 20:12:33 EDT 2008
En Sat, 29 Mar 2008 07:33:40 -0300, Steven D'Aprano
<steve at REMOVE-THIS-cybersource.com.au> escribió:
> 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()
Would this help (untested)?
def main():
return timeit.Timer('func()', 'from __main__ import factory; func =
factory()').timeit()
Or maybe:
def main():
global func
func = factory()
return timeit.Timer('func()', 'from __main__ import func').timeit()
--
Gabriel Genellina
More information about the Python-list
mailing list