Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách lấy timer ticks (thời gian CPU) tại một thời điểm trong Python

Hàm time.time() trả về số giây (float) từ epoch UTC. Đây là "wall-clock time", không phải CPU ticks thuần túy. Để lấy CPU time, dùng time.process_time() (Python 3.3+).

1. time.time() - Wall-clock timestamp

import time

ticks = time.time()
print(ticks)  # 1514823178.6920464
  • Trả về float giây từ epoch (1970-01-01 UTC).
  • Độ phân giải: thường 1µs (Linux) hoặc 1-10ms (Windows).
  • Có thể giảm nếu giờ hệ thống bị lùi lại.

2. time.process_time() - CPU time (Python 3.3+)

import time

start = time.process_time()
# CPU-intensive work
sum(i*i for i in range(10**7))
end = time.process_time()

print(f"CPU time used: {end - start:.6f} giây")
  • Chỉ tính thời gian CPU của process hiện tại.
  • Không tính sleep, I/O wait.
  • Monotonic (không giảm).

3. time.perf_counter() - High-res wall-clock

start = time.perf_counter()
time.sleep(0.1)
end = time.perf_counter()
print(f"Wall time: {end - start:.6f}")  # ~0.1

So sánh

HàmLoạiMonotonicDùng cho
time.time()Wall-clock (epoch)❌Timestamp, log, cache expiry
time.perf_counter()Wall-clock (relative)✅Benchmark, elapsed time
time.process_time()CPU time✅Profiling thuật toán
time.clock()Deprecated-Tránh dùng

Lưu ý

"Ticks" trong Python thường chỉ giá trị float giây từ time.time(). Không có khái niệm "CPU ticks" thô như C (clock_t).