Đo tốc độ thực thi code Python có 2 cấp độ: đo nhanh một lần (profiling sơ bộ) và benchmark thống kê (chính xác).
1. Đo nhanh một lần: time.perf_counter()
import time
start = time.perf_counter()
# code cần đo
print("Hello")
end = time.perf_counter()
print(f"Elapsed: {end - start:.8f} seconds")
2. Benchmark chính xác: timeit
Module timeit chạy code nhiều lần, tắt garbage collector, trả về thống kê.
import timeit
def f(x):
return x * x
# number=100000: chạy inner loop 100k lần
# repeat=3: lặp toàn bộ 3 lần
times = timeit.repeat(
"for x in range(100): f(x)",
setup="from __main__ import f",
number=100000,
repeat=3
)
print("Raw times:", times)
print("Best (min):", min(times))
print("Average:", sum(times)/len(times))
Kết quả mẫu
Raw times: [2.064, 2.088, 2.052]
Best (min): 2.052
Average: 2.068
3. Command line usage
python -m timeit -n 100000 -r 3 "for x in range(100): f(x)"
Mẹo hay
- Dùng
timeit.default_timer(tự chọn perf_counter/time.time phù hợp platform). - Tăng
numbercho code nhanh, giảm cho code chậm. - Luôn xem
min(loại bỏ nhiễu GC, context switch), không phải average. - Tránh
time.clock()(deprecated).