这段代码:
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/