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.
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.
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:
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.
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():
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
timeitwhen you need reliable comparisons between implementations. - Prefer
monotonic()for deadlines and timeouts. - Avoid treating wall-clock functions such as
time.time()ordatetime.now()as precise benchmarking tools.
Related reading
- How do I merge a list of dicts into a single dict?
- How do I merge two dictionaries in a single expression in Python?
- How do I merge two lists of tuples based on a key?
- How do I mock an open used in a with statement using the Mock framework in Python?
- How do I move a file in Python?
- How do I move a file in Python?
- How do I override __getattr__ without breaking the default behavior?
- How do I parallelize a simple Python loop?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.