Equivalent to GetTickCount() on Linux

2019-01-09 05:16发布

问题:

I'm looking for an equivalent to GetTickCount() on Linux.

Presently I am using Python's time.time() which presumably calls through to gettimeofday(). My concern is that the time returned (the unix epoch), may change erratically if the clock is messed with, such as by NTP. A simple process or system wall time, that only increases positively at a constant rate would suffice.

Does any such time function in C or Python exist?

回答1:

You can use CLOCK_MONOTONIC e.g. in C:

struct timespec ts;
if(clock_gettime(CLOCK_MONOTONIC,&ts) != 0) {
 //error
}

See this question for a Python way - How do I get monotonic time durations in python?



回答2:

This seems to work:

#include <unistd.h>
#include <time.h>

uint32_t getTick() {
    struct timespec ts;
    unsigned theTick = 0U;
    clock_gettime( CLOCK_REALTIME, &ts );
    theTick  = ts.tv_nsec / 1000000;
    theTick += ts.tv_sec * 1000;
    return theTick;
}

yes, get_tick() Is the backbone of my applications. Consisting of one state machine for each 'task' eg, can multi-task without using threads and Inter Process Communication Can implement non-blocking delays.



回答3:

You should use: clock_gettime(CLOCK_MONOTONIC, &tp);. This call is not affected by the adjustment of the system time just like GetTickCount() on Windows.



回答4:

Yes, the kernel has high-resolution timers but it is differently. I would recommend that you look at the sources of any odd project that wraps this in a portable manner.

From C/C++ I usually #ifdef this and use gettimeofday() on Linux which gives me microsecond resolution. I often add this as a fraction to the seconds since epoch I also receive giving me a double.