How to Measure Speed of Python Code

Speed of the python code indicates performance. The timeit module in python is inbuilt, and you can use it for this purpose.

Python timeit

What is timeit module?

With the timeit module, we target a snippet of code and it will run that code millions of times, in order to give us the statistically most relevant value for the code execution time. Note that the default value for the number of times the code is executed is 1000000.

Program using timeit

First step, import the timeit module, then use the methods (related to timeout) to get the execution time. Below, you’ll find two examples demonstrate the usage of it.

To illustrate, the first example uses for loop, and the second one uses lambda function. Therefore you can see the difference in execution time.

Code example to use timeit

import timeit
code_to_measure = '''
def func1():
    numbers = []
    for x in range(1000):
      numbers.append(x*2 + x**2)
measure = timeit.timeit(stmt = code_to_measure, number = 10000)
print("Execution time for function func1: ", measure)
code_to_measure = '''

The output has two statements. One is the execution time of the func1, and the second is for func2.

The output

The func2 took more time than func1. The time measurement is in seconds.

Execution time for function func1:  0.0016275793313980103

Execution time for function func2:  0.017717315815389156

** Process exited - Return Code: 0 **
Press Enter to exit terminal

The key code of timeit

The “measure” object collects the time. It is a statistical time of 10000 times code executes internally and gets the time.

Also, read


Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.