You are currently viewing How to Measure Elapsed Time in Python?

The most simple approach to measure elapsed time in Python is to use the time module. To measure the elapsed time first you need to get the time before the execution of the main code and then after the execution of the code, and finally, calculate the difference between the two. There are more advanced pythonic ways to find elapsed time, which we will discuss in this article.

Advertisements

1. Quick Examples to Measure Elapsed Time in Python

These examples will give you a high-level idea of how to measure elapsed time using different methods. However, we will discuss each of them in detail.


import time
import datetime

# Example 1 - Using the time module's time() function
start_time = time.time()
# Code which we find elapsed Time
print('Doing something')
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time}")

# Example 2 - Using the datetime module's datetime.now() function
start_time = datetime.datetime.now()
# Code to time goes here
end_time = datetime.datetime.now()
elapsed_time = (end_time - start_time).total_seconds()
print(f"Elapsed time : {elapsed_time}")

2. Use Python time Module to Measure Elapsed Time

The time module in Python is a simple way to measure elapsed time using the time() function. This function returns the number of seconds since the Unix epoch (January 1, 1970), which can be used to calculate the elapsed time between two points in code.

To use this function, follow the below steps:

  1. Import the time module.
  2. Call the time() function at the start of the code section.
  3. Call the time() function again at the end of the code section.
  4. elapsed time is the subtraction of the start time from the end time.

See below code example:


# Import time module
import time

# Before the execution
start_time = time.time()

# Put your code here
# - - - - 
# - - - - 

# After the code is executed
end_time = time.time()

# The differnce is the elapsed time
elapsed_time = end_time - start_time
print("Elapsed time: {elapsed_time} seconds")

3. timeit module – Measuring Elapsed Time

In Python, the timeit module is a more accurate way to measure the execution time of small code snippets using the timeit() function. This function runs the given code snippet multiple times and returns the average time taken for each run, which reduces the effect of random fluctuations in performance.

To use the timeit() function, we need to pass the code to be timed as a string to the stmt parameter and specify the number of times to run the code using the number parameter.

See the below example:


# Import timeit
import timeit

code_to_time = """
import random
lst = [random.randint(1, 100) for _ in range(1000)]
lst.sort()
"""

elapsed_time = timeit.timeit(stmt=code_to_time, number=1000)
print(f"Elapsed time: {elapsed_time:} seconds")

However, we can also put the code in a function and pass it to the stmt parameter. This will produce the same result. See the following basic syntax for using the timeit module for calculating elapsed time.


# Using a function
import timeit

def my_function():
    # Code to time goes here
    pass

elapsed_time = timeit.timeit(stmt=my_function, number=1000)
print(f"Elapsed time: {elapsed_time:} seconds")

4. monotonic() – Accurate Elapsed Time

The monotonic() function from the time module returns a clock that is not affected by system clock adjustments or other processes running on the system. This makes it a useful function to measure elapsed time in Python.

To use the monotonic() function, you should store the current time value before and after the code section you want to time, calculate the elapsed time by subtracting the start time from the end time, and print the elapsed time in a human-readable format.

See the following example:


import time

start_time = time.monotonic()

# Code to time goes here
lst = [i**2 for i in range(1000000)]

end_time = time.monotonic()

elapsed_time = end_time - start_time

print(f"Elapsed time: {elapsed_time:} seconds")

5. pref_counter() – Elapsed Time for Short Intervals

This function returns the value of a performance counter, which is a clock that tracks the time elapsed since an arbitrary starting point. Unlike the time() function, perf_counter() is not affected by system clock updates and can provide more accurate measurements of short intervals.

To use perf_counter(), you simply call the function twice, once at the beginning of the code you want to measure and again at the end, and then subtract the initial time from the final time to calculate the elapsed time.


import time

start_time = time.perf_counter()

# Code to measure elapsed time for
lst = [i**2 for i in range(1000000)]

end_time = time.perf_counter()

# Elapsed time is the differnce
elapsed_time = end_time - start_time

print(f"Elapsed time: {elapsed_time:} seconds")

6. Comparison – Use case for Each method

We have discussed 4 different methods to find the elapsed time of a code. Though there are other methods to do so. Yet each method has a different use case and you might know where to use which method.

  1. time() function: It may not provide high accuracy for short intervals due to system clock updates. Use this function for general-purpose timing when high accuracy is not required.
  2. timeit() module: This module provides a more accurate and reliable way to measure elapsed time by executing a code snippet multiple times and calculating the average time. Use this module for benchmarking and comparing the performance of different code snippets or functions.
  3. monotonic() function: This function is similar to perf_counter(), but it is designed to provide more accurate measurements of short intervals by using a clock that is not affected by system clock updates. Use this function when you need to measure very short intervals with high accuracy.
  4. perf_counter() function: This function provides high accuracy and is not affected by system clock updates, making it a good choice for measuring short intervals. Use this function when high accuracy is required and system clock updates could cause errors

7. Summary and Conclusion

We have discussed the different ways to find the elapsed time for a code in python. Though there are multiple ways, by now you know which one to pick. I hope this article was helpful. If you have any questions, please leave them in the comment section.

Happy Coding!