Passing function objects to timeit

George Sakkis george.sakkis at gmail.com
Mon Mar 31 15:29:27 CEST 2008


On Mar 31, 6:15 am, Peter Otten <__pete... at web.de> wrote:
> George Sakkis wrote:
> > On Mar 30, 9:03 am, Peter Otten <__pete... at web.de> wrote:
> >> Steven D'Aprano wrote:
> >> > On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote:
>
> >> >> Second try:
> >> > ...
> >> >> Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing
> >> >> with each call. But it's the only way I could find, at least without
> >> >> changing the code template used by timeit.
>
> >> > Eeek. Talk about namespace pollution.
>
> >> > Thanks for the effort, but if that's the only solution, I think the
> >> > solution is worse than the problem!
>
> >> > Perhaps it's time for me to take a different approach.
>
> >> [snip]
>
> >> Maybe the following enhancement of timeit would be worthwhile?
>
> > [snip]
>
> > That would be great. I sometimes avoid timeit altogether because
> > setting up the environment is so cumbersome. Can you post the patch to
> > bugs.python.org so it doesn't get lost ?
>
> Looking into
>
> http://svn.python.org/view/python/trunk/Lib/timeit.py?rev=54953&view=...
>
> I discovered that the Python developers took a different approach and timeit
> now allows callables for setup and statement:
>
> >>> def f(): print 42
> ...
> >>> timeit.Timer(f).repeat(1, 1)
>
> 42
> [3.3855438232421875e-05]
>
> So my patch is probably a case of instant obsolescence...
>
> Peter

I'm afraid that the taken approach is worse than your patch. For one
thing, it allows only zero-arg functions. Of course one can work
around it by passing "lambda: f(...)" but that's adding extra overhead
which can be measurable for small fast functions. Even if passing
*args and **kwds to a Timer is allowed, that's still going to be
slower (because of tuple unpacking and whatnot) as Steven's attempt
above showed.

I think it's at least worth bringing this to the attention of the
developers.

George



More information about the Python-list mailing list