Python Program to Measure the Elapsed Time in Python
Elapsed time refers to the amount of time that has passed since a certain event or process started. It can be measured in various units of time such as seconds, minutes, hours, days, weeks, months, or years. For example, if you start running at 10:00 AM and finish at 10:30 AM, the elapsed time for your run would be 30 minutes. Elapsed time is often used to measure the duration of tasks or events, and can be calculated by subtracting the start time from the end time.
Python Code :
The below Python program measures the elapsed time between two points in your code:
# Import the time module
import time
# Get the current time using the time() function
start_time = time.time()
# Your code goes here...
# Get the current time again
end_time = time.time()
# Calculate the elapsed time
elapsed_time = end_time - start_time
# Print the elapsed time in seconds
print(f"The elapsed time is {elapsed_time:.2f} seconds.")
In this program, we first import the time module, which provides access to various time-related functions.
We then use the time() function to get the current time in seconds since the epoch. We assign this value to the variable start_time.
Next, we include your code between the two time measurements.
After the code is executed, we get the current time again and assign it to the variable end_time.
We then calculate the elapsed time by subtracting the start_time from the end_time. We assign this value to the variable elapsed_time.
Finally, we print the elapsed time using an f-string with a format specifier (:.2f) to round the elapsed time to two decimal places.
You can include any code you like between the two time measurements. The elapsed time will be measured in seconds, so if your code takes less than one second to execute, the elapsed time will be a decimal value less than 1. If your code takes more than one second to execute, the elapsed time will be an integer value equal to or greater than 1.