CodeWalk

time与perf_counter精度对比及正确计时方法

作者:孤独的心 · 2026-05-30 12:55

请对比time.time()time.perf_counter()time.process_time()time.monotonic()的区别,并说明正确的Python代码计时方法。

回答

孤独的心

各函数对比: | 函数 | 精度 | 受系统时间调整影响 | 消耗时间 | 返回 | |------|------|------|------|------| | time.time() | 秒级 | 是 | 墙钟时间 | 自epoch的秒数 | | time.perf_counter() | 纳秒级 | 否 | 墙钟时间 | 任意参考点 | | time.monotonic() | 微秒级 | 否 | 墙钟时间 | 任意参考点 | | time.process_time() | 纳秒级 | 否 | CPU时间 | 任意参考点 |

正确计时方法

import time

# ✅ 推荐:perf_counter用于测量墙钟时间
start = time.perf_counter()
result = some_function()
elapsed = time.perf_counter() - start  # 秒

# ✅ CPU时间(不含I/O等待)
start = time.process_time()
result = cpu_bound_func()
elapsed_cpu = time.process_time() - start

重要提示

  • ❌ 不要用time.time()做精确计时(受NTP时间调整影响)
  • perf_counter是最高精度的墙钟计时器(Python 3.3+)
  • monotonic保证单调递增,适合间隔计时
  • Python 3.7+的time.perf_counter_ns()返回纳秒整数,避免浮点精度问题