如何在python中获得单调的持续时间? [英] How do I get monotonic time durations in python?
问题描述
我想记录实际时间在墙上花费多长时间.目前,我正在这样做:
I want to log how long something takes in real walltime. Currently I'm doing this:
startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
但是,如果在运行SQL查询(或任何其他查询)时调整了时间,那将失败(产生错误的结果).
But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running.
我不想仅仅对其进行基准测试.我想将其登录到实时应用程序中,以查看实时系统上的趋势.
I don't want to just benchmark it. I want to log it in a live application in order to see trends on a live system.
我想要诸如clock_gettime(CLOCK_MONOTONIC,...)之类的东西,但是在Python中.并且最好不必编写一个调用clock_gettime()的C模块.
I want something like clock_gettime(CLOCK_MONOTONIC,...), but in Python. And preferably without having to write a C module that calls clock_gettime().
推荐答案
该函数非常简单,您可以使用ctypes来访问它:
That function is simple enough that you can use ctypes to access it:
#!/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中获得单调的持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!