用亚秒精度比较时间

2024-04-25 01:01:26 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

我看到很多人建议time.time()。虽然time.time()是一种精确测量一天中实际时间的方法,但它并不能保证给你毫秒级的精度!来自文档:

Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

这是而不是比较两次时所需的过程!它会以许多有趣的方式爆炸,而你却不知道发生了什么。事实上,当你比较两次的时候,你并不需要知道一天中的哪个时间,只需要知道这两个值有相同的起点。为此,time库提供了另一个过程:time.clock()。文件上说:

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.

使用time.clock()


或者,如果您只想测试代码的运行速度,您可以方便地使用^{}来为您进行所有的度量,这实际上是度量代码执行过程中所用时间的标准方法。

int(time.time() * 1000)会做你想做的。time.time()通常返回一个浮点值,该值自epoche以来具有双精度计数秒数,因此将其相乘不会损害精度。

对于@kqr:time.clock()的误导性回答,另一个词并没有给出纪元的时间。它为您提供进程在Unix的CPU上运行的时间,或者自第一次调用Windows上的函数以来经过的时间,请参见python docs

同样,docs声明time.time()也不能保证给您ms精度。虽然这句话主要是为了确保你不依赖于嵌入式或实际的硬件,我不知道任何例子,你实际上不会得到微软的精度。

如果可能的话,time.time() * 1000将为您提供毫秒精度。

相关问题 更多 >