Python Timeit

Python Timeit() with Examples

Table of Contents

timeit.timeit(stmt, setup,timer, number)

In Python timeit function the first input “stmt” takes the code as input for which you want to measure execution time. Let’s run a simple program.

import timeit
print(timeit.timeit(‘2+3’))

In the above code, a simple addition command is given as input. The time taken to perform simple addition is shown below.

Python Timeit() with Examples

Multiple lines as input

In the below example, time it function is taking multiple lines of code as input. While giving multiple lines as the input you just need to separate the statements by a semicolon.

import timeit
print(timeit.timeit(‘x = 2;y = 3; sum= x + y’))
Python Timeit() with Examples

Using triple quotes

Let’s take a look at the code in which we can pass a whole program or function as input to the python timeit function. 

import timeit
import_module = “import math”
testcode = ”’
def test():
x = 2
math.sqrt(x)
”’
print(timeit.repeat(stmt=testcode, setup=import_module,repeat = 1))

In the below screenshot 1 represents the second input of the timeit function. The “Setup” takes the necessary dependencies of the code that are required.

Python Timeit() with Examples

Comparison of two codes

Now let’s take a look at how to compare two different sets of code. We are going to compare two python functions, addition and multiplication.

import timeit


def addition(x, y):
result = x + y
return result


def multiplication(x, y):
result = x * y
return result


def addition_time():
# compute addition time
SETUP_CODE = '''
from __main__ import addition '''
TEST_CODE = '''
addition(2,3)
'''

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

# minimum time
print('addition time: {}'.format(min(times)))


# compute multiplication time
def multiplication_time():
SETUP_CODE = '''
from __main__ import multiplication'''
TEST_CODE = '''
multiplication(2,3)
'''

# timeit.repeat statement
times = timeit.repeat(setup=SETUP_CODE,
                      stmt=TEST_CODE,
                      repeat=3,
                      number=10000)

# minimum time
print('multiplication time: {}'.format(min(times)))


if __name__ == "__main__":
multiplication_time()
addition_time()

The following is the output.

Python Timeit() with Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class