实现说明
演示用的数据放在这几个模块级绑定中: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())