timeit – Measure execution time of small bits of Python code

less than 1 minute read

timeit is a standard python package and it provides a simple way to time small bits of Python code.

>>> from timeit import timeit
>>> timeit('pow(2,100)')
3.0458367670330517
>>> timeit('2**100')
0.036938466936362602

This timeit function takes a statement to be timed, and a setup statement (to initialize variables, for example). The timeit function runs the code many times (default one million) and takes an average of the timings.

>>> timeit('2**100', number=1)
1.7267552721023094e-06

In addition to the programmatic interface, timeit provides a command line interface for testing modules.

$ python  -m timeit   "import math;math.pow(2,100)"
1000000 loops, best of 3: 1.76 usec per loop

Categories:

Updated: