To measure the elapsed time of a process in Python, use the time module to find the starting time and ending time, and then subtract the two times.
import time
starting_time = time.time()
print("Process started...")
print("Process ended...")
ending_time = time.time()
print(ending_time - starting_time)
#Output:
0.0018320083618164062
When creating Python programs, the ability to easily benchmark and calculate the elapsed time of a program can be very useful.
You can easily calculate the elapsed time of a piece of Python code with the help of the time module.
The time() function from the time module gets the current time. We can use time() to get the starting time, the ending time and then take the time difference to get the time elapsed.
Below is a simple example in Python of how to get the elapsed time in seconds.
import time
starting_time = time.time()
print("Process started...")
print("Process ended...")
ending_time = time.time()
print(ending_time - starting_time)
#Output:
0.0018320083618164062
Formatting the Elapsed Time of Program in Python
When subtracting two times in Python, we get the time elapsed in seconds. However, sometimes we want to format the time elapsed so it’s easier to read and understand.
We can use the timedelta() function from the datetime module to create a timedelta object which will format the time elapsed.
When printed to the console, timedelta objects print HH:MM:SS.
Below is how to convert the time elapsed to a timedelta object in Python.
import time
from datetime import timedelta
starting_time = time.time()
print("Process started...")
print("Process ended...")
ending_time = time.time()
print(timedelta(seconds=ending_time - starting_time))
#Output:
0:00:00.001832
Hopefully this article has been useful for you to learn how to measure and print the time elapsed in a Python program.