Timeit module wrapper

A simple, easy to use wrapper function for doing quick tests of your functions using the timeit module.


The timeit module provides an easy way of testing the performance of your Python code by running it in many iterations and averaging the timings.

However it is not very obvious how to write a simple test case using timeit for the first time. This wrapper provides an easy to use interface for it.

For example to time your function 'test' defined in module 'mymodule' and assuming the Timeit function is saved in 'timer.py'...

from mymodule import test from timer import Timeit Timeit(test) 0.57 usec/pass

#!/usr/bin/python
# A simple wrapper for the timeit module.
import timeit

def Timeit(func,number=10000,module="__main__"):
    """ A wrapper which can
    be used to time any function """

    name = func.__name__
    t = timeit.Timer("%s()"%name, "from %s import %s" % (module, name))
    return "%.2f usec/pass" % (1000000*t.timeit(number=number)/number)

if __name__=="__main__":
    from mymodule import test
    
    # Using wrapper
    print Timeit(test)
    # Directly using timeit
    t = timeit.Timer("test()", "from __main__ import test")
    print "%.2f usec/pass" % (1000000*t.timeit(number=10000)/10000)    

code.activestate.com ↗