58

我想记录一些东西在真正的墙上用了多长时间。目前我正在这样做:

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

但是,如果在 SQL 查询(或任何它是)运行时调整时间,这将失败(产生不正确的结果)。

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

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

4

5 回答 5

83

该函数非常简单,您可以使用 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()
于 2009-07-30T10:33:40.613 回答
45

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

于 2013-01-19T16:49:11.957 回答
9

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

在 Python 的 C 头文件中可移植地获取正确的常量#defined 是很棘手的;有 h2py,但这并不能真正帮助您在运行时获得价值。

于 2010-12-20T01:03:00.737 回答
4

这是我在 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.

编辑:在信任之前检查上述内容是否适用于您的目标操作系统。单调库似乎可以处理某些操作系统而不是其他操作系统中的时钟变化。

于 2018-01-28T21:54:27.707 回答
0

time.monotonic()可能有用:

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

于 2017-05-08T09:16:38.433 回答