To measure the execution time of a program in Python, use the time module to find the starting time and ending time. After you have the starting time and ending time, 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 calculate and display the execution time of a program can be very useful.
You can easily calculate the execution 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 total time that our program is executing.
Below is a simple example in Python of how to get the total execution time of a block of code 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 Execution Time of Program in Python
When subtracting two times in Python, we get the total execution time in seconds. However, sometimes it can be useful to be able 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 that it took our program to execute.
When printed to the console, timedelta objects print HH:MM:SS.
Below is how to convert the execution time to a timedelta object and print it to the console 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 execution time of a Python program in Python.