How do I get monotonic time durations in python?

前端 未结 5 883
感情败类
感情败类 2020-11-27 03:09

I want to log how long something takes in real walltime. Currently I\'m doing this:

startTime = time.time()
someSQLOrSomething()
print \"That took %.3f secon         


        
5条回答
  •  日久生厌
    2020-11-27 04:05

    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 
    
    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()
    

提交回复
热议问题