How to Measure Elapsed Time in Python
Last Updated : 23 Apr, 2025
In Python, we can measure the elapsed time (time taken for a specific task to complete) on executing a code segment or a Python script. It's useful when we are benchmarking the code, debugging or optimizing performance.
Python provides several built-in modules to measure the execution time of code blocks:
- timeit: Best for benchmarking small code snippets.
- time: Flexible and good for general timing.
- datetime: Useful for human-readable timestamps.
Using timeit Module
The timeit module is designed to provide precise timings by:
- Disabling garbage collection temporarily.
- Repeating execution multiple times for consistency.
Example 1: Basic Usage of timeit.timeit()
In this example, we will analyze how to use the timeit module and use it to find the execution time of a lambda expression.
Python import timeit exec_time = timeit.timeit("print('Hello World!')", number=5) print(exec_time, "secs")
OutputHello World! Hello World! Hello World! Hello World! Hello World! 8.779999916441739e-06 secs
Explanation:
- timeit.timeit(stmt, number): Executes stmt ( statement as a string) number times and returns total time in seconds.
- Default number of execution is 1_000_000.
Example 2: Measuring a Code Block
In this example, we'll write a Python code segment having a function and it's call as a string and pass it to timeit.timeit() function.
Python import timeit code = '''\ import random def run(n): return n**n run(random.randint(20, 50)) ''' exec_time = timeit.timeit(code, number=10**6) print(f"{exec_time:.3f} secs")
Output:
3.692 secs
Explanation:
- Use this format for multi-line code or code requiring imports.
- Pass the entire block as a string.
Example 3: Repeating Timing with timeit.repeat()
Instead of using timeit.timeit(), we can use timeit.repeat() to run the same code multiple times automatically. It repeats the test and returns a list of results, making it easier to analyze average or consistent execution time without writing extra loops.
Python import timeit def square(n): return n ** 2 times = timeit.repeat(lambda: square(3), number=10, repeat=5) for i, t in enumerate(times, 1): print(f"Run {i}: {round(t * 1e6, 2)} µs")
OutputRun 1: 4.16 µs Run 2: 2.04 µs Run 3: 1.97 µs Run 4: 1.68 µs Run 5: 1.47 µs
Explanation:
- timeit.repeat(): Returns a list of timing results.
- Helps analyze performance over multiple runs.
Example 4: Using timeit.default_timer()
timeit.default_timer() uses the timeit.perf_counter() to record the timestamp of an instance in nanoseconds and we can subtract end time from start time to get the execution time duration in nanoseconds.
Python import timeit def square(n): return n ** 2 s = timeit.default_timer() square(11111111) e = timeit.default_timer() print(f"Elapsed: {round((e - s) * 1e6, 3)} µs")
Explanation:
- default_timer() uses perf_counter() under the hood.
- Gives high-resolution timestamps.
Using time Module
In Python time module, there are different methods to record and find the execution time of a given code segment. It provides functions like
- perf_counter()
- time_ns()
- process_time()
Example 1: time.perf_counter()
time.perf_counter() method records the time in seconds time unit. Since our sample function is very simple, so, we need to convert it to micro seconds to get time difference value in readable format.
Python import time def square(n): return n ** 2 start = time.perf_counter() square(3) end = time.perf_counter() print(f"Elapsed: {(end - start) * 1e6:.3f} µs")
Explanation:
- time.perf_counter() provides the highest available resolution timer in Python, ideal for measuring short durations.
- we capture the start time before running the function and end time after.
- elapsed time is then calculated in microseconds for readability.
Example 2: time.time_ns() (Nanosecond Precision)
To measure the elapsed time or execution time of a block of code in nanoseconds, we can use the time.time_ns() function.
Python import time def square(x): return x ** 2 start = time.time_ns() square(3) end = time.time_ns() print("Time taken", end - start, "ns")
Explanation:
- time.time_ns() is similar to time.time() but returns time in nanoseconds.
- It’s suitable when we need very high precision, like benchmarking ultra-fast code.
Example 3: time.process_time() (CPU Time)
time.process_time() function returns the sum of the system and the user CPU time.
Python import time def heavy_calc(n): return n ** 76567 start = time.process_time() heavy_calc(125) end = time.process_time() print("CPU Time:", (end - start) * 1e3, "ms")
OutputCPU Time: 21.163569 ms
Explanation:
- process_time(): Measures CPU time, ignores sleep and I/O delays.
- Good for profiling CPU-bound tasks.
Using datetime Module
Use datetime when human-readable timestamps are preferred.
Example: datetime.now()
Python from datetime import datetime def square(n): return n ** 2 s = datetime.now() square(3) e = datetime.now() elapsed = (e - s).total_seconds() * 1e6 print("Elapsed:", elapsed, "µs")
Also read: timeit.repeat(), time.process_time().
Similar Reads
How to Measure Elapsed Time in C++?
Measuring elapsed time is a common requirement for most software development packages. It is used to determine the efficiency of the program and gives an idea of which parts of the program takes which much time. This helps in optimizing the code, such that improves its execution time. In this articl
3 min read
How to add time delay in Python?
In this article, we are going to discuss how to add delay in Python. How to add Time Delay?In order to add time delay in our program code, we use the sleep() function from the time module. This is the in-built module in Python we don't need to install externally.Time delay means we are adding delay
5 min read
How to Measure Script Execution Time in PHP?
Measuring the script execution time in PHP is the time required to execute the PHP script. To calculate script execution time use clock time rather than the CPU execution time. Measuring script execution time is useful to check and improve the execution time for better application performance. Measu
2 min read
How to Measure Execution Time of Function in R ?
In this article, we will learn how to measure the execution or running time of a function in the R programming language. Method 1: Using Sys.time For this first create a sample function that runs for a specific duration. For doing so pass the duration to Sys.sleep() function. Syntax:   startTime
4 min read
How to set an input time limit in Python?
In this article, we will explain how to set an input time limit in Python. It is one of the easiest programming languages which is not only dynamically typed but also garbage collected. Here we will look at different methods to set an input time limit. Below are the methods we will use in this artic
6 min read
How to capture SIGINT in Python?
The signal module performs a specific action on receiving signals. Even it has the ability to capture the interruption performed by the user through the keyboard by use of SIGINT. This article will discuss SIGINT only, how to capture it, and what to do after it has been captured. Modules Required: S
3 min read
How to Minimize Python Script Execution Time?
Minimizing Python script execution time is essential for improving performance, especially in production environments, competitive programming (CP) or data structures and algorithms (DSA). Faster execution ensures better user experience in apps and helps us perform well in coding challenges. In this
3 min read
Timeit in Python with Examples
The timeit module in Python accurately measures the execution time of small code snippets, offering more consistent results than time.time() by avoiding background interference and disabling garbage collection. Itâs ideal for comparing code performance, benchmarking and optimization and can be used
3 min read
Python | time.time_ns() method
Time module in Python provides various time-related functions. This module comes under Pythonâs standard utility modules. time.time_ns() method of Time module is used to get the time in nanoseconds since the epoch. To get the time in seconds since the epoch, we can use time.time() method. The epoch
2 min read
Python | time.process_time_ns() method
Time module in Python provides various time-related functions. This module comes under Pythonâs standard utility modules. time.process_time_ns() method of time module in Python is used to get the sum of the system and user CPU time of the current process in nanoseconds. This method does not include
5 min read