Change language

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)"  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.

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically