Open In App

How to Measure Elapsed Time in Python

Last Updated : 23 Apr, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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

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

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

Output
Elapsed: 1.263 µ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")

Output
Elapsed: 1.549 µ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")

Output
Time taken 1504 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")

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

Output
Elapsed: 10.0 µs

Also read: timeit.repeat(), time.process_time().


Next Article
Practice Tags :

Similar Reads