Skip to content

Instantly share code, notes, and snippets.

@notslang
Last active February 8, 2024 06:26
Show Gist options
  • Save notslang/5eb39b3dbb65eecf1f7dab1c4253cd12 to your computer and use it in GitHub Desktop.
Save notslang/5eb39b3dbb65eecf1f7dab1c4253cd12 to your computer and use it in GitHub Desktop.
get difference between timespecs
/**
* Subtract timespec `b` from `a`. timespec `a` must be greater than `b`.
* @param res Where we put the result
* @param a timespec pointer for end time
* @param b timespec pointer for start time
*/
void get_difference(timespec *res, timespec *a, timespec *b) {
if (a->tv_nsec < b->tv_nsec) {
res->tv_sec = a->tv_sec - b->tv_sec - 1;
res->tv_nsec = a->tv_nsec - b->tv_nsec + 1000000000;
} else {
res->tv_sec = a->tv_sec - b->tv_sec;
res->tv_nsec = a->tv_nsec - b->tv_nsec;
}
}
/**
* Convert a timespec into a long represending the number of milliseconds in
* that interval.
* @param interval
* @return The number of milliseconds in the interval that the timespec
* represents, as a double.
*/
long timespec_to_ms(timespec *interval) {
return (long)interval->tv_sec * 1000 + (long)interval->tv_nsec / 1e6;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment