Understanding timeit in Python

In this tutorial, we will learn about timeit module in Python. Python provides various methods to determine the execution time of a piece of code.
One way is to use the Python inbuilt time module (time is saved before and after the program) and another with more accuracy is timeit module.

Using Python timeit module:

When a program is running, there are many processes running in the background of the program.
Time module ignores the execution time of the background processes, therefore we use the timeit module to measure the accurate performance of a program. It runs your Python piece of code millions of times (1000000) to get you the
accurate output.

timeit.timeit()

Generally, timeit() function has four keywords as arguments and each has a string value –
1. setup executes first. It contains declared variables and imported modules.
2. stmt is a primary statement that’s the execution time has to be found is assigned to stmt keyword.
3. timer is an object that has a sensible default value so you do not have to bother about it.
4. number is the number of executions that you have to run the primary statement.
timeit() function returns output in seconds.

Example:

import timeit #importing the required module i.e timeit
primary_stmt="import math"
#piece of code that's execution time has to be measured
code='''
def square():
    list=[]
    for i in range(1000):
        list.append(sqrt(i))'''
#implementing timeit.timeit function
print(timeit.timeit(setup=primary_stmt,stmt=code,number=100))

 

First time on running the program the output is :

9.139999999996373e-05

Second time on running the program the output is :

 
5.4400000000009996e-05

Third time on running the program the output is :

4.370000000009089e-05

Here we can see, when we run the same program multiple times, on each performance, there is a reduction in output.

I hope, this will help you to understand the concept of timeit module theoretically and practically.

Leave a Reply

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