Get the execution time of your Python code easily

In Python it is interesting to display the execution time of your code, it gives an idea of the speed of your algorithm.

That’s why we will see in this article how to do it !

Execution time

Raw format

First of all let’sdisplay the execution time in raw format.

For that we use the time package.

In fact, we will simply store the time it is when we start our algorithm.

Then, the algorithm is executed (here we chose to repeat the square of i).

Then we subtract the current time from the time we had stored :

import time

start = time.time()

for i in range(10000):
  i**i

print(time.time() - start)

Output : 6.517595529556274

This simply gives us the time that has elapsed between the start and the end of the execution.

Here, 6.5 seconds.

HH:MM:SS format

To have a more intuitive format, we may also use the ctime() function.

This function will simply allow us to convert the raw format into date & time format.

Once this date & time format is obtained, we extract solely the hours, minutes and seconds.

This gives us :

import time

start = time.time()

for i in range(10000):
  i**i

print(time.ctime(time.time() - start)[11:19])

Output : 00:00:06

Personally, I find the latter format easily understandable and favor it in my Machine Learning algos.

Take the one that best suit your needs !

That’s all for this article. Feel free to check our other tips for Python developers.

sources :

Tom Keldenich
Tom Keldenich

Data Engineer & passionate about Artificial Intelligence !

Founder of the website Inside Machine Learning

Leave a Reply

Your email address will not be published.

Beginner, expert or just curious?Discover our latest news and articles on Machine Learning

Explore Machine Learning, browse our most recent notebooks and stay up to date with the latest practices and technologies!