How to Measure Elapsed Time in Python

How to Measure Elapsed Time in Python

In Python, time elapsed is the time a code takes to execute a task or run a session, etc. The need to measure elapsed time in Python could be important while debugging, analyzing, or optimizing the code. Measuring how long a function takes to run, or finding the duration of your session, is very important for many applications. Python gives us various libraries to take care of high-resolution timing. In this blog, you will explore all the methods to measure the elapsed time in Python along with detailed examples.

Table of Contents:

What is Elapsed Time in Python?

Elapsed time in Python refers to the duration between two points during the time of executing code. It is often used to measure performance, benchmark processes, or running time for a function, etc. Python provides several tools to calculate elapsed time accurately, including the time, datetime, and timeit modules. When it comes to optimizing code or simply monitoring execution speed, understanding the basics of measuring elapsed time in Python is a skill that will improve the efficiency and performance of your program.

Master Python Course and Unlock Your Career
Explore Python Course
quiz-icon

Methods to Measure Elapsed Time in Python

Now let’s explore the different approaches for measuring the elapsed time in Python.

Method 1: Using the time Module in Python 

The time.time() function in the time module is a simple and effective way to measure elapsed time. What this does is return the number of seconds since the epoch (January 1, 1970, 00:00:00 UTC).

Example:

Python

Output

Using the time Module in Python

Explanation: Here, the time.time() method calculates the time taken by time.sleep(3). The difference between end_time and start_time gives you the elapsed time in the code. The unit of time is seconds.

Pros time.time() in Python

  • Quite simple and easy to use
  • Works on all platforms
  • Good for measuring longer durations.

Cons time.time() in Python

  • Can be affected by system clock changes.
  • This function cannot be highly precise for short time intervals.
  • Inconsistency under multi-threaded environments.

Method 2: Using the time.perf_counter() function in Python

The time.perf_counter() function in Python provides a higher resolution timer that doesn’t change even when the system clock changes, making it ideal for benchmarking.

Example:

Python

Output:

time.perf_counter()

Explanation: Here, this function in Python performs much better for smaller durations as it gives a high-resolution timer that remains unaffected by system clock changes or updates.

Pros of time.perf_counter() in Python

  • The method carries high resolution.
  • Not affected by system clock changes.
  • Best for short code and testing for performance.

Cons of time.perf_counter() in Python

  • Only available in versions above Python 3.3.
  • This method is also not consistent with the total sampling time and may vary each time.
  • Not exactly human-readable as it returns a float.

Method 3: Using the time.process_time() function in Python 

time.process_time() in Python measures the time registered in the CPU taken by the program, excluding the sleep time.

Example:

Python

Output:

time.process_time()

Explanation: Here, the function is useful for measuring CPU-intensive tasks. It also ignores time spent in sleep or waiting for input/output.

Pros of time.process_time() in Python

  • Measures the actual time taken by the CPU.
  • This method also ignores I/O wait time and sleep.
  • Highly consistent in CPU measurements.

Cons of time.process_time() in Python

  • Not the best method for measuring total execution time.
  • Not the best method to rely on as it cannot give precise time.
  • Not useful in the case of wall-clock time benchmarking.

Get 100% Hike!

Master Most in Demand Skills Now!

Method 4: Using the datetime Module for Elapsed Time in Python

This particular module in Python gives us the datetime.now() for the measurement of elapsed time.

Example:

Python

Output:

datetime Module

Explanation: Here, the date.timedelta object is responsible for giving the elapsed time in a human-readable format.

Pros of datetime.now() in Python

  • This method has a human-readable format.
  • This method is useful for logging timestamps.
  • Can provide full-time stamps with time and date.

Cons of datetime.now() in Python

  • Lower precision compared to time.per_counter()
  • Lower accuracy as well, thus not a trustworthy output. Also, garbage collection can occur.
  • Can get affected by changes in the system clock.

Method 5: Using the timeit Module in Python 

This module in Python provides a better and accurate way to measure execution time for small code snippets.

Example:

Python

Output:

timeit Module

Explanation: The timeit.timeit() runs the function multiple times, in this case 1500 times, and then reports the total time taken. This makes the method more reliable for its performance benchmarking.

Pros of timeit Module in Python

  • It’s best suited for benchmarking.
  • It also eliminates overhead from other operations.
  • Also eliminates overhead from unrelated operations.

Cons of timeit Module in Python

  • This method is not suitable in the long run.
  • Also, the results carry variability.
  • A little harder to use for complex and parameterized functions.

Comparison of Elapsed Time Measurement Methods in Python

Method Precision Uses System Clock When to Use It
time.time() Low as it depends on the system clock, which is not very precise Yes General time measurement
time.perf_counter() High as it uses a steady timer, which is also good for small time gaps No Precise benchmarking
time.process_time() High as it counts only CPU time and skips waiting time No CPU execution time
datetime.now() Medium as it uses the system clock, which is better for general use Yes Human-readable logs
timeit.timeit() Very high as it runs code many times, which helps in filtering out the noise No Code benchmarking

Real-World Applications of Measuring Elapsed Time in Python

In the segment below, you will learn to use measuring techniques for elapsed time in the real world.

Example 1: Measuring response time for API implementation time.perf_counter()

Python

Output

 API implementing time.perf_counter()

Explanation:  Here, initially, the timer starts using time.perf_counter(), and then we make a GET request for a sample API. Then, when the response is parsed and the requests for completion, the difference will give us how much time the API call took.

Example 2: Using timeit to benchmark 2 data cleaning methods

Python

Output

timeit to benchmark 2 data cleaning methods

Explanation: Here, the timeit.timeit() function is being used to run both the cleaning functions 1000 times. You will have to pass the function name as a string and import it using the setup parameter.

Best Practices to Measure Elapsed Time in Python

  • Whenever you decide to measure elapsed time in coding, choose the best method based on your precision requirements.
  • For basic benchmarking of code snippets, you should use the timeit module.
  • Keep in mind to avoid using time.time() for short-duration measurements.
  • Ensure external factors like background processes do not impact results.
  • Run the measurement multiple times to get a more reliable average.
Unlock Your Future in Python
Start your Python Journey for Free Today
quiz-icon

Conclusion

Elapsed time in Python can be measured using different methods depending on what you need. For basic timing, time.time() is good, while time.perf_counter() gives more accurate results. If you want to measure CPU usage, use time.process_time(). For testing how long specific code takes, timeit.timeit() is helpful. Python has many tools to help you check and improve performance based on your needs.

Further, check out our Python certification course and get ready to excel in your career with our Basic Python interview questions prepared by experts.

FAQs – How to Measure Elapsed Time in Python

Q1. Can time.time() measure execution time accurately?

The time.time() method is a suitable method for general time measurement, but it also lacks precision for short durations.

Q2. Situation where I can use time.perf_counter() over time.time()?

A situation where you would need high resolution, precise timing is not affected by system clock changes.

Q3. Can I change the unit of measured time to milliseconds?

Yes, you can multiply the elapsed time by 1000 units to get milliseconds by writing 

‘elapsed_time * 1000’.

Q4. Best possible method to benchmark a Python function?

You would need to minimize external influence and provide accurate results by using the timeit module.

Q5 How does timeit handle multiple runs for accuracy?

The module runs the function multiple times and averages the execution time to reduce the variability.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner