How do I measure elapsed time in Python?

Better Stack Team
Updated on February 3, 2023

There are several ways to measure elapsed time in Python. Here are a few options:

  • You can use the time module to get the current time in seconds since the epoch (the epoch is a predefined point in time, usually the beginning of the year 1970). To measure elapsed time, you can get the current time at the start and end of the section of code you want to measure, and then subtract the start time from the end time. Here's an example:
 
import time

# Code you want to measure goes here
start_time = time.time()

# some code
time.sleep(2)

end_time = time.time()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time} seconds")
  • Another option is to use the perf_counter function from the timeit module. This function returns the current performance counter value, which is a measure of elapsed time in seconds with a high precision. Here's an example:
 
import timeit

start_time = timeit.perf_counter()

# some code
time.sleep(2)

end_time = timeit.perf_counter()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time} seconds")
  • If you want to measure the time it takes for a specific function to run, you can use the timeit module to run the function a certain number of times and return the average time it takes to run. Here's an example:
 
import timeit

def function_to_time():
    # code to be measured goes here
    time.sleep(2)

elapsed_time = timeit.timeit(function_to_time, number=1)
print(f"Elapsed time: {elapsed_time} seconds")
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →