Tibor's Musings

Python Micro Benchmarking

timeit permits to micro-benchmark code snippets, e.g. the efficiency of list comprehensions for various Python versions.

Here are the results for Python 2.2, 2.3 and 2.4; note how the performance improves:

$ python2.2 /usr/lib/python2.4/timeit.py -n 10000 -r 5 "[i for i in range(1000)]"
10000 loops, best of 5: 348 usec per loop
$ python2.3 /usr/lib/python2.4/timeit.py -n 10000 -r 5 "[i for i in range(1000)]"
10000 loops, best of 5: 283 usec per loop
$ python2.4 /usr/lib/python2.4/timeit.py -n 10000 -r 5 "[i for i in range(1000)]"
10000 loops, best of 5: 137 usec per loop

Or, using the same Python version, one can compare the speed of the list comprehension approach against the classical functional approach:

$ python2.4 /usr/lib/python2.4/timeit.py -n 10000 -r 5 "[i for i in range(1000)]"
10000 loops, best of 5: 137 usec per loop
$ python2.4 /usr/lib/python2.4/timeit.py -n 10000 -r 5 "map(lambda x: x, range(1000))"
10000 loops, best of 5: 398 usec per loop

python