Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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.

I want something like clock_gettime(CLOCK_MONOTONIC,...), but in Python. And preferably without having to write a C module that calls clock_gettime().

like image 625
Thomas Avatar asked Oct 08 '22 14:10

Thomas


People also ask

Is python time time monotonic?

monotonic() method is used to get the value of a monotonic clock. A monotonic clock is a clock that can not go backward. As the reference point of the returned value of the monotonic clock is undefined, only the difference between the results of consecutive calls is valid.

What time time () returns in Python?

time() The time() function returns the number of seconds passed since epoch. For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).

Which of the following time function in python time module can be used to display time in variety of formats?

strftime() function converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.


1 Answers

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()
like image 83
Armin Ronacher Avatar answered Oct 24 '22 03:10

Armin Ronacher