Python 中如何测量代码执行花费的时间?
Python 测量耗时:time.perf_counter() 精确(推荐)、time.time() 简单、time.monotonic() 单调。本文对比各计时函数的差异和适用场景。
精确计时用 time.perf_counter()——高精度单调时钟,不受系统时间调整影响,是官方推荐的计时函数。
方法一:time.perf_counter()(推荐)
import time
start = time.perf_counter()
# 要计时的代码
result = sum(range(1000000))
elapsed = time.perf_counter() - start
print(f"耗时: {elapsed:.4f} 秒")
方法二:time.time()
import time
start = time.time()
# ... 代码 ...
print(f"耗时: {time.time() - start:.2f} 秒")
返回 Unix 时间戳(从 1970 年起的秒数)。简单直观,但不能按名称推定其固定精度排名,且受系统时间调整影响(NTP 校时会导致结果跳变)。
方法三:time.monotonic()
start = time.monotonic()
# ... 代码 ...
elapsed = time.monotonic() - start
单调递增,不受系统时间调整影响,实际时钟依平台/版本;现代 CPython 的 perf_counter 与 monotonic 可使用同一底层时钟。
三种函数对比
| 函数 | 精度 | 单调性 | 推荐场景 |
|---|---|---|---|
time.perf_counter() |
高分辨率,实际分辨率依系统 | 单调 | 精确计时/基准测试 |
time.monotonic() |
依系统 | 单调 | 超时控制 |
time.time() |
依系统 | 非单调(受 NTP 影响) | 日志时间戳 |
用装饰器封装
import time
import functools
def timing(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
print(f"{func.__name__} 耗时: {time.perf_counter()-start:.4f}s")
return wrapper
@timing
def slow_function():
time.sleep(1)
常见问题(FAQ)
Q:测量异步代码呢?
A:在 await 前后取 perf_counter 差值;上述同步装饰器直接包 async 函数只测创建协程,需要另写 async wrapper 并 await。
Q:需要微秒级精度怎么办?
A:time.perf_counter_ns() 返回纳秒单位整数,可避免浮点表示误差,但不保证纳秒准确度;用 time.get_clock_info 核对时钟。
Q:想看程序每行的耗时?
A:cProfile/pstats 统计函数调用;逐行分析用 line_profiler,比手动埋点高效。