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

Cách lấy thời gian thực thi của chương trình Python

Đo thời gian chạy chương trình Python: dùng time.perf_counter() cho wall-clock time, hoặc time.process_time() cho CPU time. Module timeit cho benchmark thống kê.

1. Đo wall-clock time (thời gian thực)

import time

start = time.perf_counter()

# Chương trình chính
print("Hello World")
# ...

end = time.perf_counter()
print(f"Thời gian chạy: {end - start:.6f} giây")

2. Đo CPU time (thời gian CPU tiêu thụ)

import time

start = time.process_time()
# Tính toán nặng
sum(i*i for i in range(10**7))
end = time.process_time()

print(f"CPU time: {end - start:.6f} giây")

3. Benchmark với timeit

import timeit

code = """
total = 0
for i in range(10000):
    total += i
"""

times = timeit.repeat(code, number=100, repeat=5)
print(f"Min: {min(times):.4f}s, Avg: {sum(times)/len(times):.4f}s")

4. Đo toàn bộ script từ command line

# Linux/Mac
time python script.py

# Windows (PowerShell)
Measure-Command { python script.py }

Tóm tắt khi dùng gì

Mục đíchCông cụ
Đo thời gian chạy script đơn lẻtime.perf_counter() hoặc CLI time
Đo CPU time (bỏ I/O, sleep)time.process_time()
Benchmark hàm/đoạn code nhỏtimeit
Profiling chi tiết (line-by-line)cProfile, line_profiler