Quick benchmarking of Python code with timeit

How long does [insert code snippet] take in Python? Find out with the timeit module, in Python since 2.3.

Below I time how long it takes to make a list with a 1000 zeros, [0,0,0,…], using different Python code snippets. Notice that you can time snippets directly on the commandline, without writing a script file (.py) or running the Python interpreter interactively.

Benchmarks ordered by running time

Using numpy:

$ python -m timeit 'import numpy' 'a = numpy.zeros(shape=(1,1000))'
100000 loops, best of 3: 2.38 usec per loop

Using 1000*[0]:

$ python -m timeit 'x = 1000*[0]'
100000 loops, best of 3: 5.05 usec per loop

Using list-comprehension:

$ python -m timeit 'x = [0 for x in range(1000)]'
10000 loops, best of 3: 55.2 usec per loop

Using a for loop with append():

python -m timeit 'x = []' 'for i in range(1000):' ' x.append(0)'
10000 loops, best of 3: 134 usec per loop

Using map:

python -m timeit 'map(lambda x: 0, range(1000))'
10000 loops, best of 3: 163 usec per loop

There are more examples on the timeit page. Of course you can also use the module in your Python scripts, but calling it on the command-line is extra cool somehow. It is somewhat surprising that list-comprehension is so slow, since everybody is always talking about how fast it is.

Using range(n) to generate a list [0, 1, …, 999]:

python -m timeit 'range(1000)'
100000 loops, best of 3: 10.3 usec per loop

Leave a Reply