tags:

views:

74

answers:

2

I want to know the time that has passed between the occurrence of two events.

Now, the simple way would be to use something like:

time_t x, y;
x = time(NULL);

/* Some other stuff happens */

y = time(NULL);
printf("Time passed: %i", y-x);

However, it is possible that the system time is changed between these two events.

Is there an alternative way to know the time that has passed between the two events? Or is there a way to detect changes to the system time?

+1  A: 

You can use clock_gettime() on Linux or gethrtime() on some other Unix systems. Although the difference between two such values gives you a time interval, those call are not giving you regular time values. As HP-UX says regarding gethrtime():

The gethrtime() function returns the current high-resolution real time. Time is expressed as nanoseconds since a certain time in the past.

Michael
If using clock_gettime() then you need to specify CLOCK_MONOTONIC - if supported. Using the normal option - CLOCK_REALTIME - will cause inaccuracies if the system clock is changed.
Dipstick
+5  A: 

Since you're apparently on Linux, you can use the POSIX CLOCK_MONOTONIC clock to get a timer that is unaffected by system time changes:

struct timespec ts1, ts2;

clock_gettime(CLOCK_MONOTONIC, &ts1);
/* Things happen */
clock_gettime(CLOCK_MONOTONIC, &ts2);

ts2.tv_sec -= ts1.tv_sec;
ts2.tv_nsec -= ts1.tv_nsec;
if (ts2.tv_nsec < 0)
{
    ts2.tv_nsec += 1000000000L;
    ts2.tv_sec -= 1;
}

printf("Elapsed time: %lld.%09lds\n", (long long)ts2.tv_sec, ts2.tv_nsec);

To check if the system supports CLOCK_MONOTONIC, check for sysconf(_SC_MONOTONIC_CLOCK) > 0.

caf