python - time.clock() 无法正确返回时间

标签 python time clock

这段代码:

import time

now = time.clock()
while now + 5 > time.clock():
    print time.clock()
    time.sleep(1)
    print "Woke up"

返回:

0.015718
Woke up
0.015814
Woke up
0.015942
Woke up
0.016107
Woke up
0.01625
Woke up
0.016363
正如您所看到的,返回的时间似乎没有返回以整数表示的秒数,尽管文档说它应该这样做。这里出了什么问题?

编辑:我使用的是 Mac OS X El Capitan

最佳答案

您可能应该阅读手册:

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

假设您使用的是 UNIX(fx Linux 或 iOS),则行为是正确的。 time.clock 返回进程消耗的 CPU 时间量, sleep 时不消耗任何 CPU 时间。

当然,UNIX 和 Windows 之间的差异使得此功能毫无用处,除非您检测到哪种行为正在生效并采取相应的行动。

关于python - time.clock() 无法正确返回时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37111678/

相关文章:

python - 在 Python 中将整数列表转换为字节数组

r - 如何将基于时间的不等长数据帧与R中的缓冲间隔合并?

c# - 表示日期和时间的最少字节数是多少?

java - 在 android 中拆分时间

c++ - C `clock()` 函数只返回一个零

javascript - 使用 python 解析网页上的 HTML 和脚本?

python - 在 python 中定义数组的正确方法

python - 正则表达式和一系列模式?

c - STM32L4 - SPI2 时钟问题

linux - 如何使用 ALSA 将音频时钟从属到系统时钟?