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")

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github