python 循环中的相对时钟

python relative clock in loop

假设我们有一个用 Python 编写的日志记录功能(可能不相关,但仍然如此)并且日志记录还会在日志中记录时间。

然后在永无止境的 while 循环中过了一段时间后,有人更改了系统时钟(由系统本身或系统管理员更改)。然后当然所有的时间都在日志中搞砸了(特别是如果结果是时钟已经发回了某个时间)。

有没有办法通过在 while 循环中拥有自己的相对时钟来防止这种情况发生?我想记下循环之前的时间,然后测量循环中的迭代时间并手动将其添加到保存的时间中,但是当然这在一段时间后漂移得非常糟糕。

有什么建议吗?

如果您在 UNIX 系统下工作,os.times() 不受系统时间更改的影响:

os.times()

Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children’s user time, children’s system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. On Windows, only the first two items are filled, the others are zero.

>>> import os
>>> os.times()
(0.01, 0.0, 0.0, 0.0, 17194492.75)
>>> os.times()[4]
17194500.18