Passing function objects to timeit

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Mar 30 06:28:19 CEST 2008


On Sun, 30 Mar 2008 00:27:45 -0300, Gabriel Genellina wrote:

> En Sat, 29 Mar 2008 23:23:07 -0300, Steven D'Aprano
> <steve at REMOVE-THIS-cybersource.com.au> escribió:
> 
>> The general problem is that I wish to time an arbitrary function with
>> arbitrary arguments. The function and arguments are provided to me as
>> Python objects, but timeit requires strings. Converting the objects to
>> strings is not practical, and the objects might not exist in the
>> __main__ module.
> 
> Ah, ok, I understand now. I think this is more-or-less what you want:

[snip]

No, sorry, it's still sharing state.


from timeit import Timer

# Slight modification to the function to return the Timer object.
def timeanyfunc(fn, *args, **kw):
    global wrapped_fn
    def wrapped_fn():
        return fn(*args, **kw)
    return Timer("wrapped_fn()", "from %s import wrapped_fn" % __name__)

def functionA():
    print "Function A"

def functionB():
    print "Function B"

T1 = timeanyfunc(functionA)
T2 = timeanyfunc(functionB)

T1.repeat(3, 1)  # Should print "Function A".
T2.repeat(3, 1)  # Should print "Function B".



-- 
Steven



More information about the Python-list mailing list