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 年起的秒数)。简单直观但精度不如 perf_counter,且受系统时间调整影响(NTP 校时会导致结果跳变)。
方法三:time.monotonic()
start = time.monotonic()
# ... 代码 ...
elapsed = time.monotonic() - start
单调递增,不受系统时间调整影响,但精度略低于 perf_counter。
三种函数对比
| 函数 | 精度 | 单调性 | 推荐场景 |
|---|---|---|---|
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()
result = func(*args, **kwargs)
print(f"{func.__name__} 耗时: {time.perf_counter()-start:.4f}s")
return result
return wrapper
@timing
def slow_function():
time.sleep(1)
常见问题(FAQ)
Q:测量异步代码呢?
A:同样适用,在 await 前后取 perf_counter 差值。
Q:需要微秒级精度怎么办?
A:time.perf_counter_ns() 返回纳秒整数,精度最高。
Q:想看程序每行的耗时?
A:用 cProfile + pstats 或 line_profiler 做性能剖析,比手动埋点高效。