Timeit in Python with examples

This module provides an easy way to find the execution time of small bits of Python code.

Why time?

  • Well, what about using a simple time module? Just save the time before and after executing your code and subtract them! However, this method is not accurate, as a background process may be running that interrupts the execution of the code and you will receive significant changes in the execution time of small pieces of code.
  • timeit runs your piece of code millions of times (the default is — 1000000), so you get the most statistically significant measurement of code execution time!
  • TimeIt is pretty easy to use and has a command line interface as well as a callable one.

So now let`s start exploring this handy library!

The module function timeit.timeit (stmt, setup, timer, number) takes four arguments:

  • stmt — this is the statement you want to measure; the default is “pass.”
  • setup, which is the code you run before running stmt ; the default is “pass”. 
    We usually use this to import the necessary modules for our code.
  • timer, which is a timeit.Timer object; it usually has a reasonable default so you don`t need to worry about it.
  • number, which is the number of executions you would like to run stmt .

Where timeit.timeit () returns the number of seconds it took to execute the code.

Example 1

Let`s look at a basic example first.

# import the required module

import timeit

 
# code snippet is executed only once

mysetup = "from math import sqrt"

 
# snippet of code whose execution time you want to measure

mycode = "" "

def example ():

  mylist = []

  for x in the range (100):

  mylist.append (SQRT (x) )

"" "

  
# timeit statement

print timeit.timeit (setup = mysetup,

stmt = mycode,

  number = 10000 )

  • The result of the above program will be the execution time (in seconds ) for 10,000 iterations of the code snippet passed to timeit.timeit () .

    Note: Note output is the time it takes to iterate the number times of the code snippet, and more than one iteration. For one iteration of exec. time, divide the exit time by number .

  • The program is pretty simple. All we need to do is pass the code as a string to the timeit.timeit () function .
  • It is recommended to keep import statements and other static code snippets in the customization argument.

Example 2

Let`s look at another practical example in which we compare two search methods, namely: binary search and linear search
In addition, here I will demonstrate two more features: the timeit.repeat function and calling functions already defined in our program.

# import required modules

import timeit

 
# binary search function

def binary_search (mylist, find):

while len (mylist) & gt;  0 :

mid = ( len (mylist)) / / 2

  if mylist [ mid] = = find:

return True

elif mylist [mid] & lt; find:

mylist = mylist [: mid]

else :

mylist = mylist [mid + 1 :]

return False

 

 
# linear search function

def linear_search (mylist, find):

for x in mylist:

  if x = = find:

  return True

return False

 

 
# compute binary search time

def binary_time ():

SETUP_CODE = "" "

from __main__ import binary_search
from random import r andint & # 39; & # 39; & # 39;

 

TEST_CODE = "" "

mylist = [x for x in range (10000)]
find = randint (0, len (mylist))
binary_search (mylist, find) & # 39; & # 39; & # 39;

 

# timeit.repeat statement

times = timeit.repeat (setup = SETUP_CODE ,

stmt = TEST_CODE,

repeat = 3 ,

number = 10000 )

 

# print mi minimal execution. time

print ( `Binary search time: {}` . format ( min (times))) 

 

 
# calculate linear search time

def linear_time ():

SETUP_CODE = " ""

from __main__ import linear_search
from random randint import & # 39; & # 39; & # 39;

 

TEST_CODE = "" "

mylist = [x for x in range (10000)]
find = randint (0, len (mylist))
linear_search (mylist, find)

"" "

# timeit.repeat statement

times = timeit.repeat (setup = SETUP_CODE,

  stmt = TEST_CODE,

  repeat = 3 ,

number = 10000 )

  

# print the minimum execution. time

print ( `Linear search time: {}` . format ( min (times))) 

 

if __ name__ = = "__ main__" :

linear_time ()

binary_time ()

  • The output of the above program will be the minimum value in the list times
    This is what the sample output looks like:
  • The timeit.repeat () function takes one additional argument , repeat . The output will be a list of the execution times of all code runs repeated with the specified number. times.
  • In the configuration argument we passed:
     from __main__ import binary_search from random import randint 

    This will import the definition of the binary_search function already defined in the program , and a random library function randint .

  • As expected, we noticed that the execution time of a binary search is significantly less than a linear search !

Example 3
Finally, below I will demonstrate how you can use the command line interface of the timeit module:

Here I explain each term separately:

So, this was a short but short introduction to the timeit module and its practical application. 
This is a very handy tool for Python programmers when they need a quick glance at the execution time of their code snippets.

This article is provided by Nikhil Kumar . If you like Python.Engineering and would like to contribute, you can also write an article using contrib.python.engineering, or email your article to [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.