Skip to main content
 首页 » 编程设计

python之perf_counter 的真正作用

2025年05月04日10lhb25

阅读有关 timeit.default_timer() 的文档 (Python 3.4) 它说:

The default timer, which is always time.perf_counter().

但阅读旧文档(Python 2.7)时它说:

Define a default timer, in a platform-specific manner. On Windows, time.clock() has microsecond granularity, but time.time()‘s granularity is 1/60th of a second. On Unix, time.clock() has 1/100th of a second granularity, and time.time() is much more precise.

那么,perf_counter() 是否只是做了一个保持可移植性的选择?我的意思是如果系统是 windows 它返回 time.clock(),否则 time.time(),这样上面定义的精度等级仍然保持 true,不是是吗?

简而言之,perf_counter() 是如何工作的?

请您参考如下方法:

在 Python 2.7 和 Python 3.4 之间引入了 time.perf_counter()。现在 timeit.default_timer() 不再需要为最佳时间源的选择而烦恼,因为现在已经在 time 模块中处理了。

在后台 time.perf_counter() 简单地调用最佳可用的 C API。详情在PEP 418包括对新 Python 时间 API 和操作系统的 native 时间 API 的描述。