我想记录真实壁挂时间的内容。目前我正在这样做:

startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)

但如果在SQL查询(或其他任何东西)正在运行时调整时间,则会失败(产生不正确的结果)。

我不想只是对它进行基准测试。我想在实时应用程序中记录它,以便查看实时系统的趋势。

我想要像clock_gettime(CLOCK_MONOTONIC,...)这样的东西,但是在Python中。最好不必编写调用clock_gettime()的C模块。

有帮助吗?

解决方案

该功能非常简单,您可以使用ctypes来访问它:

#!/usr/bin/env python

__all__ = ["monotonic_time"]

import ctypes, os

CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>

class timespec(ctypes.Structure):
    _fields_ = [
        ('tv_sec', ctypes.c_long),
        ('tv_nsec', ctypes.c_long)
    ]

librt = ctypes.CDLL('librt.so.1', use_errno=True)
clock_gettime = librt.clock_gettime
clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]

def monotonic_time():
    t = timespec()
    if clock_gettime(CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
        errno_ = ctypes.get_errno()
        raise OSError(errno_, os.strerror(errno_))
    return t.tv_sec + t.tv_nsec * 1e-9

if __name__ == "__main__":
    print monotonic_time()

其他提示

现在,在Python 3.3中,您将使用 time.monotonic

正如这个问题所指出的,避免使用NTP Linux上的重新调整需要CLOCK_MONOTONIC_RAW。在Linux上定义为4(从2.6.28开始)。

从Python的C头中获取正确的常量#defined是很棘手的;有h2py,但这并没有真正帮助你在运行时获得价值。

以下是我在Python 2.7中获得单调时间的方法:

安装 monotonic 包:

pip install monotonic

然后在Python中:

import monotonic; mtime = monotonic.time.time #now mtime() can be used in place of time.time()

t0 = mtime()
#...do something
elapsed = mtime()-t0 #gives correct elapsed time, even if system clock changed.

time.monotonic()可能有用:

  

返回单调时钟的值(以小数秒为单位),即不能倒退的时钟。时钟不受系统时钟更新的影响。返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top