Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to GetTickCount() on Linux

Tags:

python

c

linux

time

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?

like image 972
Matt Joiner Avatar asked Jun 02 '10 13:06

Matt Joiner


4 Answers

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?

like image 115
nos Avatar answered Nov 16 '22 13:11

nos


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.

like image 40
penguinapricotman Avatar answered Nov 16 '22 13:11

penguinapricotman


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.

like image 6
macgarden Avatar answered Nov 16 '22 12:11

macgarden


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.

like image 1
Dirk Eddelbuettel Avatar answered Nov 16 '22 11:11

Dirk Eddelbuettel