Use time.perf_counter() from Python’s built-in time module to measure the exact wall-clock execution time of a script or code block with the highest available timer resolution. Unlike time.time(), perf_counter() is monotonic, meaning it is unaffected by system clock adjustments or daylight saving changes.
Basic Example
import time
# 1. Record the high-resolution start timestamp
start_time = time.perf_counter()
# 2. Run the code or program you want to benchmark
total = sum(i * i for i in range(1_000_000))
# 3. Record the end timestamp and compute the elapsed duration
end_time = time.perf_counter()
elapsed = end_time - start_time
print(f"Execution time: {elapsed:.6f} seconds")
Key Details & Alternative Methods
- Measuring an entire script from the command line: You can time an entire Python program without modifying its source code using the built-in
timeitmodule or your shell’stimecommand:# Cross-platform via Python's timeit module python -m timeit -n 1 -r 1 "import my_script" # On Linux / macOS shells time python my_script.py - Micro-benchmarking small snippets (
timeit): For short functions or expressions (taking microseconds or milliseconds), single runs suffer from CPU background noise. Usetimeit.timeit()to run the code thousands of times automatically and disable garbage collection interference:import timeit duration = timeit.timeit("'-'.join(str(n) for n in range(100))", number=10_000) print(f"10,000 runs took: {duration:.4f} seconds") - Measuring CPU execution time only (
time.process_time()): If your program callstime.sleep()or waits on network/disk I/O and you only want to measure active CPU processing time (excluding sleep/wait time), usetime.process_time()instead oftime.perf_counter(). - Nanosecond precision (
time.perf_counter_ns()): Returns elapsed time as an integer in nanoseconds rather than a floating-point number, avoiding float precision loss on very long-running benchmarks.
Comparison of Python Timing Tools
| Timer / Tool | Measures | Affected by System Clock? | Best Used When |
|---|---|---|---|
time.perf_counter() |
Total elapsed wall-clock time (includes sleep/I/O) |
No (monotonic) | Benchmarking scripts, functions, and end-to-end execution. |
time.process_time() |
Active CPU time only (excludes sleep/I/O) |
No (monotonic) | Measuring pure CPU-bound computation efficiency. |
timeit.timeit() |
Repeated wall-clock runs of small code snippets | No | Micro-benchmarking short expressions or comparing algorithms. |
time.time() |
System wall-clock time since Unix epoch | Yes (can jump backward) | Logging human-readable timestamps, not benchmarking. |
You must log in or register to comment.
