Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 20 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#!/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)    

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

1 comment

Andreas Kostyrka 16 years, 9 months ago  # | flag

Consider autofetching the module name:

>>> def x(): pass
...
>>> import inspect
>>> inspect.getmodule(x).__name__
'__main__'
>>>

Further I'd probably iterate over sys.modules to find the name. (modules sometime do not know their name where they were loaded from.)

Andreas

Created by Anand on Mon, 28 Feb 2005 (PSF)
Python recipes (4591)
Anand's recipes (38)

Required Modules

Other Information and Tasks