Python
elapsed time
timing functions
time measurement
Python programming

How do I measure elapsed time in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Measuring elapsed time in Python is straightforward once you choose the right clock. The main distinction is whether you want a quick duration for application code or a more careful benchmark for performance work.

Use perf_counter() for Real Elapsed Time

For most timing tasks, time.perf_counter() is the right default. It provides a monotonic, high-resolution clock designed for measuring durations, so it is not affected by wall-clock changes.

python
1from time import perf_counter
2
3
4def parse_numbers() -> int:
5    return sum(i * i for i in range(100_000))
6
7
8start = perf_counter()
9result = parse_numbers()
10elapsed = perf_counter() - start
11
12print("result:", result)
13print(f"elapsed: {elapsed:.6f} seconds")

This pattern works well for scripts, data processing steps, and logging around expensive operations.

If you want reusable timing, wrap it in a context manager:

python
1from contextlib import contextmanager
2from time import perf_counter
3
4
5@contextmanager
6def timer(label: str):
7    start = perf_counter()
8    try:
9        yield
10    finally:
11        elapsed = perf_counter() - start
12        print(f"{label}: {elapsed:.6f} seconds")
13
14
15with timer("sorting"):
16    numbers = list(range(200_000, 0, -1))
17    numbers.sort()

That keeps timing code out of the business logic while still producing useful output.

Use timeit for Benchmarks

If you are comparing implementations, measure more than once. Single runs are noisy because the operating system, caches, and interpreter startup can all affect the result. The timeit module is built for this job.

python
1import timeit
2
3
4def using_loop() -> int:
5    total = 0
6    for i in range(1000):
7        total += i
8    return total
9
10
11def using_sum() -> int:
12    return sum(range(1000))
13
14
15loop_times = timeit.repeat(using_loop, repeat=5, number=10_000)
16sum_times = timeit.repeat(using_sum, repeat=5, number=10_000)
17
18print("loop best:", min(loop_times))
19print("sum best:", min(sum_times))

Here, repeat=5 runs the benchmark five times, and number=10_000 controls how many function calls happen in each run. Looking at the best or median result is usually more informative than trusting a single measurement.

Choose the Clock for the Job

Python exposes several clocks, but they are not interchangeable:

  • 'time.perf_counter() is best for elapsed time and benchmarking.'
  • 'time.monotonic() is good when you only need a stable clock, such as timeouts.'
  • 'time.time() returns wall-clock time and is useful for timestamps, not precise benchmarks.'
  • 'datetime.now() is meant for human-readable dates and logging.'

A timeout loop is a good example for monotonic():

python
1from time import monotonic, sleep
2
3
4deadline = monotonic() + 2.0
5
6while monotonic() < deadline:
7    sleep(0.2)
8
9print("timeout reached")

That code keeps working correctly even if the system clock changes while the program is running.

Common Pitfalls

The most common mistake is timing code with time.time() and assuming it is the best benchmark clock. It measures wall time, which can jump if the system clock is adjusted.

Another mistake is benchmarking only once. Short operations can vary a lot from run to run, so use timeit or run the code repeatedly yourself before drawing conclusions.

It is also easy to time the wrong thing. If file I/O, network access, logging, or setup code is mixed into the measurement, the result may say more about the environment than the code you wanted to compare. Separate setup from the operation under test whenever possible.

Finally, be careful with extremely small timings. If an operation completes in a tiny fraction of a millisecond, loop it many times and divide if needed. Otherwise the measurement overhead can dominate the result.

Summary

  • Use time.perf_counter() as the default tool for measuring elapsed time in Python.
  • Wrap repeated timing logic in a context manager when you want cleaner application code.
  • Use timeit when you need reliable comparisons between implementations.
  • Prefer monotonic() for deadlines and timeouts.
  • Avoid treating wall-clock functions such as time.time() or datetime.now() as precise benchmarking tools.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.