1
votes

Is there any way to measure elapsed time in linux/unix without using system clock? The problem is that system clock changes in some situations and elapsed time measured by time or gettimeofday or anything else like that gives incorrect result.

I'm thinking of creating separate thread which performs loop with sleep(100) inside and counts number of repetitions.

Any better solutions?

4
"performs loop with sleep(100) inside and counts number of repetitions". sleep is allowed to return late for no reason (well, no reason that your process can see), so that doesn't necessarily work. - Steve Jessop
And on what basis do you say time and gettimeofday are inaccurate? - doron
From man gettimeofday - The time is expressed in seconds and microseconds since midnight (0 hour), January 1, 1970. - C.B.

4 Answers

6
votes

std::chrono::steady_clock can be used to measure time, and takes into account changes to the system clock.

4
votes

Use monotonic time, which represents time since some point: http://linux.die.net/man/3/clock_gettime

int64_t get_monotonic_timestamp(void)
{
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (int64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
}
2
votes

Measuring elapsed time with sleep (or variants) is a bad idea. Your thread can wake up at any time after the elapsed sleep time so this is sure to be inaccurate.

1
votes

For a time delay, you can use e.g. select.