如何在python中获得单调持续时间?

Tho*_*mas 55 python linux benchmarking clock

我想记录真实壁挂时间有多长.目前我这样做:

startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
Run Code Online (Sandbox Code Playgroud)

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

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

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

Arm*_*her 77

该函数非常简单,您可以使用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()
Run Code Online (Sandbox Code Playgroud)

  • 使用`CLOCK_MONOTONIC_RAW == 4`(自Linux 2.6.28;特定于Linux)以避免NTP调整. (14认同)

Pad*_*118 37

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

  • 如果我正确阅读文档,似乎在 Python 3.3 中你可以通过调用 `time.clock_gettime(time.CLOCK_MONOTONIC_RAW)` 来获得 `CLOCK_MONOTONIC_RAW`,这很好,所以当你用它来测量小的时间间隔时,你永远不会出错当网络通过 NTP(网络时间协议)调整更新时间时引入。Python 时间参考:https://docs.python.org/3/library/time.html#time.CLOCK_MONOTONIC_RAW。&lt;-- 注意:仅适用于 UNIX/LINUX。对于 Windows,只需调用`time.clock()`,因为它使用 QueryPerformanceCounter(),它已经具有微秒或更好的分辨率。 (2认同)

Dai*_*ood 9

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

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