Reputation: 3089
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?
Upvotes: 2
Views: 820
Reputation: 239031
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
.
Upvotes: 6
Reputation: 2776
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.
Upvotes: 1