Để đo thời gian với độ chính xác cao (high-resolution), Python 3.3+ cung cấp time.perf_counter() và time.perf_counter_ns() (nano-giây, Python 3.7+).
1. time.perf_counter() - Chuẩn cao nhất
- Trả về float giây, độ phân giải nano-giây trên hầu hết hệ thống.
- Bao gồm thời gian sleep, I/O wait (wall-clock).
- Monotonic: không bị ảnh hưởng bởi thay đổi giờ hệ thống.
import time
start = time.perf_counter()
# code cần đo
end = time.perf_counter()
print(f"Elapsed: {end - start:.9f} giây")
print(f"Elapsed: {(end - start) * 1_000_000:.3f} micro-giây")
2. time.perf_counter_ns() - Trả về nguyên nano-giây (Python 3.7+)
start = time.perf_counter_ns()
# ...
end = time.perf_counter_ns()
print(f"Elapsed: {end - start} ns")
print(f"Elapsed: {(end - start) / 1_000_000:.3f} ms")
3. time.process_time() - Chỉ CPU time
- Không tính thời gian sleep, I/O wait.
- Hữu ích để đo thuật toán thuần túy.
4. So sánh độ chính xác trên các platform
| Platform | perf_counter resolution | Ghi chú |
|---|---|---|
| Linux (modern) | ~1 ns | clock_gettime(CLOCK_MONOTONIC) |
| Windows 10+ | ~100 ns | QueryPerformanceCounter |
| macOS | ~1 ns | mach_absolute_time |
⚠️ Tránh dùng
time.clock(): Deprecated 3.3, removed 3.8. Hành vi khác nhau Unix/Windows.time.time(): Độ phân giải thấp (~1-10ms), bị ảnh hưởng NTP/timezone change.
Best practice cho benchmark
import timeit
# timeit tự dùng perf_counter bên dưới
timeit.timeit("your_code()", setup="from __main__ import your_code", number=10000)