timeit module provides a simple way to time small bits of Python code. It has both command line as well as callable interfaces. It avoids a number of common traps for measuring execution times. See also Tim Peters’ introduction to the “Algorithms” chapter in the Python Cookbook, published by O’Reilly.
the command line example:
python -mtimeit -s"from math import sqrt; x = 123" "x**.5"
the module example:
>>> import timeit >>> s = """\ ... try: ... str.__nonzero__ ... except AttributeError: ... pass ... """ >>> t = timeit.Timer(stmt=s) >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) 17.09 usec/pass >>> s = """\ ... if hasattr(str, '__nonzero__'): pass ... """ >>> t = timeit.Timer(stmt=s) >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) 4.85 usec/pass