askvity

How to find time elapsed in Python?

Published in Time Measurement 3 mins read

You can find the elapsed time in Python using the time module or the datetime module by recording start and end times and calculating the difference.

Using the time module

The time module provides functions to work with time. You can use the time.time() function to get the current time in seconds since the epoch. Here's how to calculate elapsed time:

  1. Record the start time: Use time.time() to capture the time before the code block you want to measure.
  2. Execute the code block: Run the code for which you want to measure execution time.
  3. Record the end time: Use time.time() again to capture the time after the code block.
  4. Calculate the difference: Subtract the start time from the end time to get the elapsed time in seconds.
import time

start_time = time.time()

# Code block you want to measure
time.sleep(2)

end_time = time.time()

elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time:.4f} seconds")

Using the datetime module

The datetime module allows you to work with dates and times. It can be used to find elapsed time, similar to the time module. Here's how:

  1. Record the start time: Use datetime.datetime.now() to capture the current time as a datetime object.
  2. Execute the code block: Run the code you wish to time.
  3. Record the end time: Use datetime.datetime.now() again to capture the current time after the code block.
  4. Calculate the difference: Subtract the start datetime object from the end datetime object. This will result in a timedelta object representing the elapsed time.
  5. Extract seconds from the timedelta object: Use .total_seconds() to get the elapsed time in seconds.
import datetime
import time

start_time = datetime.datetime.now()

# Code block to measure
time.sleep(2)

end_time = datetime.datetime.now()

elapsed_time = end_time - start_time
elapsed_seconds = elapsed_time.total_seconds()
print(f"Elapsed time: {elapsed_seconds:.4f} seconds")

Comparison of time and datetime modules

Feature time Module datetime Module
Time Representation Seconds since epoch (float) Datetime objects
Usage Simple time measurement Complex date and time operations
Precision Can provide high precision Good precision, can use microseconds
Ease of use Simpler for elapsed time More versatile, includes date

Practical insights:

  • For simple time measurement, the time module is often sufficient and more straightforward to use.
  • The datetime module provides a robust framework when you need date and time operations, including working with different time zones or formatting date and time strings.
  • Both methods involve taking timestamps before and after a code block and then calculating the difference.
  • For very precise timing, consider using time.perf_counter() which provides the highest resolution time available on the system.

Related Articles