Passing function objects to timeit

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Mar 30 06:55:25 EDT 2008


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. Since I can't call 
timeit, and I can't inherit from it (same problem with state being shared 
between instances), perhaps I should write my own timer.


import timeit
import gc
import itertools

def timeit2(func, args=[], kwargs={}, it=None,
            timer=timeit.default_timer):
    if it is None: it = itertools.repeat(None, timeit.default_number)
    save_gc = gc.isenabled()
    gc.disable()
    try:
        start = timer()
        for counter in it:
            func(*args, **kwargs)
        end = timer()
    finally:
        if save_gc:
            gc.enable()
    return end - start



Now to go and test it.



-- 
Steven



More information about the Python-list mailing list