Measuring execution time helps identify slow operations and compare implementations. Choose the measurement method according to whether you need a single elapsed duration, a repeated benchmark, or reusable instrumentation.
1. Wall-clock time
python_snippet
Python · 5 lines|
| import time |
| start = time.time() |
| time.sleep(0.1) |
| print(f"Elapsed: {time.time() - start:.4f}s") |
time.time() is a wall clock and may change if the system clock is adjusted. For durations, prefer a monotonic performance counter.2. Performance counter
python_snippet
Python · 5 lines|
| import time |
| start = time.perf_counter() |
| time.sleep(0.1) |
| print(f"Elapsed: {time.perf_counter() - start:.4f}s") |
The elapsed duration includes sleep and I/O waits. Only the difference between readings is meaningful.
3. Repeat with timeit
python_snippet
Python · 7 lines|
| import timeit |
| def work(): |
| return sum(range(100)) |
| seconds = timeit.timeit(work, number=1000) |
| print(f"Total for 1000 calls: {seconds:.6f}s") |
timeit uses a performance counter by default. Repeat measurements when benchmarking short operations, and remember that a benchmark can be affected by its environment.4. Use a decorator
python_snippet
Python · 18 lines|
| from functools import wraps |
| from time import perf_counter |
| def timed(func): |
| @wraps(func) |
| def wrapper(*args, **kwargs): |
| start = perf_counter() |
| try: |
| return func(*args, **kwargs) |
| finally: |
| print(f"{func.__name__}: {perf_counter() - start:.6f}s") |
| return wrapper |
| @timed |
| def work(): |
| return sum(range(1000)) |
| work() |
This wrapper is for synchronous functions. To time an async function, await it inside an async wrapper:
python_snippet
Python · 20 lines|
| import asyncio |
| from functools import wraps |
| from time import perf_counter |
| def timed_async(func): |
| @wraps(func) |
| async def wrapper(*args, **kwargs): |
| start = perf_counter() |
| try: |
| return await func(*args, **kwargs) |
| finally: |
| print(f"{func.__name__}: {perf_counter() - start:.6f}s") |
| return wrapper |
| @timed_async |
| async def fetch(): |
| await asyncio.sleep(0.1) |
| return "done" |
| asyncio.run(fetch()) |
The elapsed time includes time spent awaiting. The
finally block also reports the duration if the coroutine raises or is cancelled.5. Time a block with a context manager
python_snippet
Python · 13 lines|
| from contextlib import contextmanager |
| from time import perf_counter |
| @contextmanager |
| def timer(label): |
| start = perf_counter() |
| try: |
| yield |
| finally: |
| print(f"{label}: {perf_counter() - start:.6f}s") |
| with timer("work"): |
| sum(range(1000)) |
The
finally block records time even if the operation raises; it does not suppress the exception.✦ 卷终 · 柯航存卷 ✦