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.


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.


import timeit #importing the required module i.e timeit
primary_stmt="import math"
#piece of code that's execution time has to be measured
def square():
    for i in range(1000):
#implementing timeit.timeit function


First time on running the program the output is :


Second time on running the program the output is :


Third time on running the program the output is :


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 *