How to Check the Amount of Time Elapsed in Python?

Estimated read time 2 min read

To check the amount of time elapsed in Python, you can use the time module or the datetime module. Here’s how you can do it using both approaches:

  1. Using the time module:
import time

# Get the start time
start_time = time.time()

# Perform some operations or tasks

# Get the end time
end_time = time.time()

# Calculate the elapsed time
elapsed_time = end_time - start_time

print("Elapsed Time:", elapsed_time, "seconds")

In this example, we use the time.time() function to retrieve the current time in seconds since the epoch (January 1, 1970). We store the start time before the operations and the end time after the operations. Subtracting the start time from the end time gives us the elapsed time in seconds.

  1. Using the datetime module:
import datetime

# Get the start time
start_time = datetime.datetime.now()

# Perform some operations or tasks

# Get the end time
end_time = datetime.datetime.now()

# Calculate the elapsed time
elapsed_time = end_time - start_time

print("Elapsed Time:", elapsed_time)

In this approach, we use datetime.datetime.now() to retrieve the current date and time as a datetime object. We store the start time before the operations and the end time after the operations. Subtracting the start time from the end time gives us a datetime.timedelta object representing the elapsed time.

Both methods allow you to measure the elapsed time for different parts of your code or tasks. You can customize the code by adding additional operations or tasks between the start and end time measurements.

Note that the elapsed time is in seconds, but you can convert it to other units (e.g., milliseconds, minutes) by performing appropriate calculations on the elapsed_time value.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply