Time Your Python Code Right: perf_counter, timeit, cProfile
Use the right clock and the right tool: perf_counter for timing, timeit for benchmarks, cProfile for profiling.
Reviewed by System Admin · Dec 2, 2026 · Editorial standards
Visual breakdown
InteractiveTime Your Python Code Right: perf_counter, timeit, cProfile — Visual Breakdown
timeit
- ✓Runs a small snippet many times
- ✓Reports a stable average duration
- ✓Good for comparing two short expressions
- ✓Not for finding slow functions in a program
cProfile
- ✓Records per-function call counts and time
- ✓Good for finding the slow part of a program
- ✓Adds overhead to the run
- ✓Not for micro-benchmarks of tiny snippets
The simple version
No jargonYou want to know how long a piece of Python code takes. The first instinct is to call time.time() before and after. That number can jump around. The system clock can be adjusted, and it has low resolution. Python's time.perf_counter() is built for measuring short durations. It uses a high-resolution clock that only moves forward. A simple pattern is start = time.perf_counter(), run your code, then elapsed = time.perf_counter() - start. You can wrap that pattern in a class, a context manager, or a decorator so you do not repeat it. A context manager is an object you use with a with block. It runs setup code when the block starts and cleanup code when the block ends. For small snippets, use timeit. It runs the snippet many times and reports a stable average. That helps when a single run is too fast to measure. For finding which function is slow, use cProfile. It records how often each function is called and how much time it spends. cProfile is a profiler, a tool that reports per-function costs. This is analysis, not a description of a specific product: the choice depends on your question. Are you timing one block? Use perf_counter. Comparing two tiny snippets? Use timeit. Hunting a slow function in a larger program? Use cProfile.
Why it matters in production
Implementation & syntax
import time
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, *args):
self.elapsed = time.perf_counter() - self.start
print(f"elapsed: {self.elapsed:.6f}s")
with Timer():
total = sum(range(1_000_000))Check your understanding
Quick Concept Check
Test your understanding in 15 seconds
You want to know which function in a larger program is consuming the most time. Which tool fits that question?
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.