← 中文资源

简体中文版本

perf_counter 测量耗时不带墙上跳变

monotonic 与 perf_counter 只前进不回退,是测量耗时的正确时钟;time.time() 是墙上时间,留给时间戳、日志与调度场景。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

monotonic elapsed >= 0: True
perf_counter saw the ~10ms sleep: True
time.time() is a wall timestamp: True
they are different clocks: True

实现说明

演示用的数据放在这几个模块级绑定中:start、work、elapsed、measured。

使用要点

  • 演示输出是带标签的(monotonic elapsed >= 0:、perf_counter saw the ~10ms sleep:、time.time() is a wall timestamp:),每个操作都会留下自己的一行标注。

常见问题

除了语言工具链还要下载什么吗?

除了这个语言的工具链,什么都不用再下载。 全部导入都来自标准库:time。 状态都挂在模块顶层:start、work、elapsed。

代码示例

import time

# time.time() is a wall clock: NTP steps or manual changes can move it backwards,
# so differences measured across it are not reliable durations
# perf_counter() and monotonic() never go backwards — they are for durations
start = time.monotonic()
work = sum(i * i for i in range(100_000))
elapsed = time.monotonic() - start
print("monotonic elapsed >= 0:", elapsed >= 0)

# perf_counter() offers the highest resolution available on the platform
start = time.perf_counter()
time.sleep(0.01)
measured = time.perf_counter() - start
print("perf_counter saw the ~10ms sleep:", 0.005 <= measured < 0.2)

# Rules of thumb: monotonic()/perf_counter() for "how long did this take",
# time.time() for "what is the wall-clock timestamp" (schedules, logs, storage)
print("time.time() is a wall timestamp:", time.time() > 1_500_000_000)
print("they are different clocks:", time.monotonic() < time.time())