Python time.monotonic() 单调时钟,返回浮点数(单位:秒)
time.monotonic()
Python 3.3 新增,单调时钟,返回浮点数(单位:秒)
import time
t0 = time.monotonic()
time.sleep(2)
t1 = time.monotonic()
print(t1 - t0) # 得到流逝的时间,≈2.0
✅ 核心特性
- 单向递增,永不回退 不受 NTP 网络校时、手动修改系统时间影响。
哪怕你把电脑系统时间往回调,
monotonic()的值依然只会变大,不会出现负数时长。 - 基准起点无意义 返回值本身没有绝对时间含义(不是 Unix 时间戳),只有两次调用的差值才有效。不能用来判断 “现在是几点”,只能算时间间隔、超时。
- 包含系统休眠 / 挂起的时间(Linux/macOS):机器休眠时,时钟依然继续走。
- 配套:
time.monotonic_ns(),返回纳秒整数,避免浮点数精度损失(Python 3.7+)
🆚 和 time.time() 对比(重点)
表格
| 函数 | 时钟类型 | 用途 | 风险 |
|---|---|---|---|
time.time() |
墙上时钟(wall-clock) | 获取当前绝对时间戳 | 系统时间被回拨 → 算出负的时间差 |
time.monotonic() |
单调时钟 | 计时、超时、定时器 | 不能转成日期 / 时刻 |
场景举例:写网络超时、epoll 等待超时、任务耗时统计,优先用
monotonic(),不要用time.time()。
🆚 和 time.perf_counter() 对比(容易混淆)
perf_counter():性能计数器,精度更高;不包含系统休眠时间。适合短时间、精细性能测试。monotonic():适合长耗时、业务超时逻辑(网络 IO、epoll、任务超时),休眠时间会计入。
底层系统调用
- Linux:
CLOCK_MONOTONIC - Windows:
QueryPerformanceCounter - macOS:
mach_absolute_time()
典型使用场景(IO 多路复用 /epoll 常用)
# epoll 超时控制示例
start = time.monotonic()
timeout_sec = 5.0
ready = epoll.poll(timeout=timeout_sec * 1000)
elapsed = time.monotonic() - start
写 IO 事件循环、定时器、连接超时,行业标准做法就是用
monotonic,防止系统时间跳变导致超时逻辑错乱。
⚠️ 禁忌
❌ 不要保存 monotonic() 的值到文件、数据库,跨进程 / 重启后基准点完全不一样,无法对比。
❌ 不能用来获取当前日期、北京时间。

浙公网安备 33010602011771号