Timeit! Python

by Jarrett Retz November 7th, 2020
programming python timeit

What is the timeit module?

The timeit module is a trustworthy way to test small blocks (or bits as mentioned in the documentation​) of Python code. You might think that testing Python code is quite straightforward:

  • Start a timer
  • Run some code
  • Stop the timer

However, there are small factors that can skew your results that are not easy to spot on the surface level.

How to Use the timeit Module

There are two avenues for using the module. You can use the Python interface or the command-line interface. This article is going to look at using the Python interface in Python's IDLE program.

One of the first things that you have to get used to when using the module is submitting the Python code (that you want to test) as a string.

I am trying to test if it's faster to append items to a variable to create a list or use a list comprehension. Therefore, I need two statements.

>>> test_block_one = """\
ls = []

for i in range(11):
    ls.append(i)

"""
>>> test_block_two = """\
ls = [i for i in range(11)]
"""

Our desired output for this code statement is:

ls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Testing Code Statements

Now that we have our two statements we can call the timeit() function on the timeit module.

# Import timeit module
>>> import timeit

# Run first test
>>> timeit.timeit(stmt=test_block_one, number=10000)
# 0.011754705999919679

# Run second test
>>> timeit.timeit(stmt=test_block_two, number=10000)
# 0.007789632000140045

# Divide results for comparison
>>> 0.011759 / 0.007789
# 1.509693157016305

We passed 10000 into the number argument to get a more accurate comparison. This represents the number of times the statement is called.

Wow, using a list comprehension is ~1.5 times faster than appending to a variable!

Including Global Variables and Namespaces

The function call can get messy if your have multiple functions to test or if you need to import other modules to test the Python code.

The timeit() function takes an argument to include the current global variables so your function stays easy to read.

This isn't relevant in our function, but it would look like:

timeit.timeit(stmt=test_block_one, number=10000, globals=globals())


Have a thought about the article?

Send JRTS a message!

We'll use this email to respond to your message.

Contact