How to Measure Function Runtime in Python

In this tutorial, we will learn how to create timer functions in Python to measure the performance of any function in a program.


To do this, we will make use of the Python time package. This will allow us to create Unix timestamps at the start and end of a function that we can compare to deduce runtime.


Let's look at an example timer function and break it down.


import time

start = time.time()

for r in range(1,40000000):

end = time.time()

print(format(end - start))


In the above example we generate a new Unix timestamp before the code to test using time.time() and store it in a variable called start – the same is done after the code and stored in the variable end.


Then we subtract the timestamps to get the difference in seconds. In the above case, it took Python 1.28 seconds to loop 40 million times.