I have a function that uses difftime to detect the time in seconds since the communication heartbeat has stopped. This function could run as fast as every 50 milliseconds. The
Before querying time, read the time(7) man page (and read it again).
The, I suggest using clock_gettime(2) with e.g. CLOCK_MONOTONIC
or CLOCK_REALTIME
, and preferably use double
for time calculations (since a struct timespec
is generally larger than any integral type).
Don't use uint16_t
for such time calculations.
Try using
inline double double_gettime (clockid_t cid) {
struct timespec ts = {0,0};
clock_gettime(cid, &ts);
return (double)ts.tv_sec + 1.0e-9*ts.tv_nsec;
}
You might want to make that function fancier, by testing if clock_gettime
is failing and giving NAN
when it fails! This is left as an exercise to the reader. You could also, for CLOCK_REALTIME
etc, measure the difference between some time at start of process and the current time (i.e. compute a struct timespec
of differences and convert that difference to a double
)
Then things like
double tstart = double_gettime(CLOCK_REALTIME);
some_long_computation();
double tend = double_gettime(CLOCK_REALTIME);
printf ("needed %f seconds to compute\n", tend-tstart);
See also clock(3)