Python “timeit” with Examples


This tutorial explains how to use the Python timeit library.

When developing proper software or an algorithm to do certain tasks, optimization is an important aspect to consider. You’re undoubtedly going to try different variations and make changes to attempt to speed up your code. But how are you going to measure any improvements in the execution time?

The answer is the timeit library in Python. This Python library will run a piece code thousands, or even millions of time’s to achieve the most accurate possible result.

If you were previously using the datetime library to try and measure execution time, you should know that its error margin is much higher than time it.


Python timeit Example

Here we’ll explain (with examples) how to use the Python timeit library effectively. We’ll be using two

You don’t have to think too much about the two functions below and how they actually work. That’s not really the point here after all, rather it’s how timeit will calculate and compare the execution times of both,

def sort(array):
  lesser = []
  greater = []
  equal = []

  if len(array) > 1:
    pivot = array[0]
    for x in array:
      if x < pivot:
        lesser.append(x)
      if x > pivot:
        greater.append(x)
      if x == pivot:
        equal.append(x)    
    return sort(lesser) + equal + sort(greater)
  else:
    return array

def bubbleSort(array): 
    n = len(array) 
  
    for i in range(n-1): 
        for j in range(0, n-i-1): 
            if array[j] > array[j+1] : 
                array[j], array[j+1] = array[j+1], array[j] 
    return array

Using timeit

The next step is to create two more functions, from which we’ll be calling our previous two functions. These two new functions are also responsible for holding the python timeit code.

def test1():
   SETUP_CODE = '''
from __main__ import sort
from random import randint'''

Now we need to create two variables, SETUP_CODE and TEST_CODE (these names are arbitrary). SETUP_CODE will store the code for any libraries that you might require as well as the importing the (previously created) function to be used.

   TEST_CODE = '''
array = []
for x in range(1000):
  array.append(randint(1,10000))
sort(array)
  '''

TEST_CODE will store the code that timeit is going to run, which includes the function call to our previously created functions. The purpose of the list, for loop and random library here is to create a list of 1000 random integers. We will then call the function using this list as a parameter.

  times = timeit.repeat( setup = SETUP_CODE,
                          stmt = TEST_CODE,  
                          number = 100) 

  print('quick sort time: {}'.format(min(times)))

Finally we have the add in the timeit code and our test function is complete. The number parameter defines the number of operations to be executed on the code.

Repeat parameters

There is another parameter called repeat which you can use to “”repeat” process many times. This helps get you a more accurate result as it returns a list of times required (5 times for a repetition value of 5).

It’s good practice to only consider the minimum time due to possible interferences by other processes in the system. For this reason we use the min() function on times (a list).

The default value of repeat is 5 and the default value of number is a million. We simply kept the number a little low to ensure a quick calculation.


Full Code

This is the full code for both timeit functions and their function calls. The only thing missing is the actual bubblesort and quicksort functions which you can find at the start of the article. Copy paste both of them into a single file if you actually want to run this code.

def test1():
  SETUP_CODE = '''
from __main__ import sort
from random import randint'''
  
  TEST_CODE = '''
array = []
for x in range(1000):
  array.append(randint(1,10000))
sort(array)
  '''
  times = timeit.repeat( setup = SETUP_CODE,
                          stmt = TEST_CODE,  
                          number = 100) 

  print('quick sort time: {}'.format(min(times)))


def test2():
  SETUP_CODE = '''
from __main__ import bubbleSort
from random import randint'''
  
  TEST_CODE = '''
array = []
for x in range(1000):
  array.append(randint(1,10000))
bubbleSort(array)
  '''
  times = timeit.repeat( setup = SETUP_CODE,
                          stmt = TEST_CODE, 
                          number = 100)

  print('bubble sort time: {}'.format(min(times)))

Take a good look at the way we indented the code within TEST_CODE. You must not indent any of the code unless it’s within a code block or is a nested statement. Indenting it to make it “fit in” better, will lead Python to believe there is meant to be a space(s) before the code when it runs it, causing errors.

Output

At the end of the code you have to actually call the two timeit functions we created in order to begin the comparison.

if __name__ == "__main__":
  test1()
  test2()

The following output was displayed on screen after running the code.

quick sort time: 0.4018649000000001
bubble sort time: 10.441018399999997

As we can see, quicksort was a much faster way of sorting the list of values than bubblesort. With this, the purpose of using timeit has been fulfilled.


This marks the end of the Python Timeit with examples tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments