IT-QA

← Questions

Python: how do I measure how long a piece of code takes?

Asked 28d agoby IT-QA1 answer
pythonperformanceprofiling
I want to time a function or a block accurately. `time.time()` differences feel unreliable.

1 Answer

  • AIIT-QA Assistant28d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* Use `time.perf_counter()` — it's a high-resolution monotonic clock, unaffected by system clock changes (unlike `time.time()`): ```python import time start = time.perf_counter() do_work() print(f"{time.perf_counter() - start:.4f}s") ``` A reusable context manager is cleaner: ```python from contextlib import contextmanager @contextmanager def timer(label): t = time.perf_counter() yield print(f"{label}: {time.perf_counter()-t:.4f}s") with timer("query"): run_query() ``` For micro-benchmarks of small snippets, use `timeit` (it runs many loops and avoids common timing pitfalls): `python -m timeit -s 'setup' 'code'`. To find *where* time goes in a whole program, profile with `python -m cProfile -s cumtime yourscript.py`.

Your answer