util/time: add timespec_add()

This commit is contained in:
Simon Ser 2022-10-04 12:11:54 +02:00
parent 293d78777d
commit 639bacdb9a
2 changed files with 22 additions and 4 deletions

View file

@ -23,6 +23,12 @@ int64_t timespec_to_nsec(const struct timespec *t);
*/
void timespec_from_nsec(struct timespec *r, int64_t nsec);
/**
* Add two timespec values `a` and `b`, and store the result in `r`.
*/
void timespec_add(struct timespec *r, const struct timespec *a,
const struct timespec *b);
/**
* Subtracts timespec `b` from timespec `a`, and stores the difference in `r`.
*/

View file

@ -25,12 +25,24 @@ uint32_t get_current_time_msec(void) {
return timespec_to_msec(&now);
}
void timespec_sub(struct timespec *r, const struct timespec *a,
void timespec_add(struct timespec *r, const struct timespec *a,
const struct timespec *b) {
r->tv_sec = a->tv_sec - b->tv_sec;
r->tv_nsec = a->tv_nsec - b->tv_nsec;
if (r->tv_nsec < 0) {
r->tv_sec = a->tv_sec + b->tv_sec;
r->tv_nsec = a->tv_nsec + b->tv_nsec;
if (r->tv_nsec >= NSEC_PER_SEC) {
r->tv_sec++;
r->tv_nsec -= NSEC_PER_SEC;
} else if (r->tv_nsec < 0) {
r->tv_sec--;
r->tv_nsec += NSEC_PER_SEC;
}
}
void timespec_sub(struct timespec *r, const struct timespec *a,
const struct timespec *b) {
struct timespec tmp = {
.tv_sec = -b->tv_sec,
.tv_nsec = -b->tv_nsec,
};
timespec_add(r, a, &tmp);
}