diff --git a/include/util/time.h b/include/util/time.h index 76ec2d7f1..5ab4cb103 100644 --- a/include/util/time.h +++ b/include/util/time.h @@ -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`. */ diff --git a/util/time.c b/util/time.c index e3a4590ad..c02e585b5 100644 --- a/util/time.c +++ b/util/time.c @@ -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); +}