How to measure time in Python

Andrey Ivanov
2 min readApr 1, 2021

It is quite often, that we need to measure the execution time of a piece of code in Python. When we want to do that, it is very easy to fall into the trap of time module.

But how time flows in the computers?

For example, assume we have a while loop:

i = 0
while i < 10000:
i += 1

If we want to measure that piece of code, then we can use time module. A lot of you know about it. It helps you to work with time in Python and has a built-in function time(), that returns you the time since the Epoch. We will use it as follows:

import time
start = time.time()

i = 0
while i < 10000:
i += 1

end = time.time()
print(end-start)

It is a great method, but…

The truth is — that method is broken. If your computer changes its system time during the execution of the code, then you will see wrong values. The thing is that time.time() gets the computer’s local time, but that is not exactly what we want. We can run a program that will execute for 3 seconds, but during that period, we will just adjust the time. Therefore, we cannot use time.time() to measure the time, but what we can use is…

A much better way is to use time.monotonic(). That function works as time.time() does. The only difference — we create a new monotonic clock, that cannot be changed even if we change our computer time. All you need to do is replace time.time() with that monotonic function.

Thanks for the reading! That was my first article, and my new to that sphere. However, if you want to hear my voice, or see me coding, then make sure to check out my Youtube channel called Python on Papyrus. Also, I made a course on Udemy, so if you want to learn one cool framework on Python, then go HERE. Alright, that is all that I wanted to tell you today. Make fun, code, and good luck!

--

--

Andrey Ivanov
0 Followers

Hello! I'm just a python programmer :)