In Python, the easiest way to print the time a program takes is with the Python time module. Below shows how to print time elapsed using Python.

import time

start = time.time()
for i in range(100):
    x = 1

end = time.time()

elapsed_time = end-start

print("elapsed time in seconds: " + elapsed_time )

#Output:
elapsed time in seconds: 0.00024127960205078125

When working with Python programs, the ability to know exactly how long your program takes, or how long certain sections of your program takes, can be very beneficial.

We can easily print time elapsed of a program using the Python time module.

The time module time() function gets the current time. We can get the current time before a block of code and get the current time after a block of code, and then subtract the two times to get the elapsed time.

Below is how to get the elapsed time of a Python program and print it.

import time

start = time.time()
for i in range(0,100000):
    x = 0

end = time.time()

elapsed_time = end-start

print(elapsed_time)

#Output:
0.015827178955078125

Formatting the Time Elapsed in Python

When working with times in Python, it can be useful to format them to be able to understand exactly the time that has passed in a program.

We can format the time elapsed of a program in Python easily with the timedelta() function from the Python datetime module.

For example, if we want to format the time elapsed as “hh:mm:ss” and print it to the console, we can do so as shown in the following Python code.

import time
from datetime import timedelta

start = time.time()
for i in range(0,1000000):
    x = 0

end = time.time()

elapsed_time = end-start

print("elapsed time: " + str(timedelta(seconds=elapsed_time)))

#Output:
elapsed time: 0:00:00.031208

Hopefully this article has been helpful for you to learn how to calculate and print time elapsed in Python.

Categorized in:

Python,

Last Update: February 26, 2024