Passing function objects to timeit

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Mar 29 23:20:34 EDT 2008


On Sat, 29 Mar 2008 21:12:33 -0300, Gabriel Genellina wrote:

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

Alas, this does not work, because all the Timer instances share the same 
state.



import timeit, time

def test_timer(func1, func2):
    global gFUNC
    gFUNC = func1
    T1 = timeit.Timer('gFUNC()', 'from __main__ import gFUNC')
    gFUNC = func2
    T2 = timeit.Timer('gFUNC()', 'from __main__ import gFUNC')
    print "Calling %s" % func1.__name__
    T1.repeat(3, 1)
    print "Calling %s" % func2.__name__
    T2.repeat(3, 1)

def functionA():
    print "Function A"

def functionB():
    print "Function B"



And here's the results:

>>> test_timer(functionA, functionB)
Calling functionA
Function B
Function B
Function B
Calling functionB
Function B
Function B
Function B



-- 
Steven



More information about the Python-list mailing list