1

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?

axe
  • 2,331
  • 4
  • 31
  • 53
  • "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 Jan 02 '14 at 16:07
  • 3
    And on what basis do you say time and gettimeofday are inaccurate? – doron Jan 02 '14 at 16:09
  • From `man gettimeofday` - The time is expressed in **seconds** and **microseconds** since midnight (0 hour), January 1, 1970. – C.B. Jan 02 '14 at 16:19

4 Answers4

6

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

IInspectable
  • 46,945
  • 8
  • 85
  • 181
Sean
  • 60,939
  • 11
  • 97
  • 136
  • 1
    To add to this answer, for sleeping there is [`sleep_for`](http://en.cppreference.com/w/cpp/thread/sleep_for) and [`sleep_until`](http://en.cppreference.com/w/cpp/thread/sleep_until). – Some programmer dude Jan 02 '14 at 16:15
  • Looks like a great solution to the problem, but looks like it's not yet supported by the gcc version we use. – axe Jan 02 '14 at 16:16
4

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;
}
Vadim Kalinsky
  • 928
  • 8
  • 18
2

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.

doron
  • 27,972
  • 12
  • 65
  • 103
  • I don't need it to be very accurate, but when system time changes I get thousands of hours as elapsed time instead of couple of seconds. – axe Jan 02 '14 at 16:12
  • 1
    This doesn't actually answer the question. You reject the solution offered in the question, but haven't offered any other solution of your own. – Rob Kennedy Jan 02 '14 at 16:14
1

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

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621