Subtract two timespec objects; find difference in time or duration

Viewed 2614

The clock_gettime function requires a struct timespec object as an argument.

https://linux.die.net/man/3/clock_gettime

In the date and time utilities section of the C standard library, there is a function difftime which calculates the difference in two time_t objects.

https://en.cppreference.com/w/c/chrono

However there does not appear to be an equivalent function for struct timespec data.

I guess it is trivial to write one given that there are just two fields inside of a struct timespec (one for the number of seconds and one for the number of nanoseconds). However, it seems surprising that the standard library does not include this function for convenience.

Here is an example of how to do it:

(time_stop.tv_sec - time_start.tv_sec)
    + 1.0e-9 * (time_stop.tv_nsec - time_start.tv_nsec);

Does a function to find the difference in time between two struct timespec objects exist? Or is it perhaps not included because clock_gettime can be called with different arguments for different types of clock?

1 Answers

However, it seems surprising that the standard library does not include this function for convenience.

difftime() returns seconds, regardless of the time units and type used for time_t.

time_t is some real type, often in seconds, but not specified as such.

difftime() performs the subtraction and returns seconds. User code cannot as there is no seconds per time_t constant,

struct timespec is specified to use seconds and nanoseconds, so a time difference in units and desired type is readily code-able.


Perhasp as:

struct timespec diff_timespec(const struct timespec *time1,
    const struct timespec *time0) {
  assert(time1 && time1->tv_nsec < 1000000000);
  assert(time0 && time0->tv_nsec < 1000000000);
  struct timespec diff = {.tv_sec = time1->tv_sec - time0->tv_sec, .tv_nsec =
      time1->tv_nsec - time0->tv_nsec};
  if (diff.tv_nsec < 0) {
    diff.tv_nsec += 1000000000;
    diff.tv_sec--;
  }
  return diff;
}

OR

double diff_timespec(const struct timespec *time1, const struct timespec *time0) {
  return (time1->tv_sec - time0->tv_sec)
      + (time1->tv_nsec - time0->tv_nsec) / 1000000000.0;
}

time.h is missing much: mktime_utc(), robust timezone support, etc.

Related