diff options
Diffstat (limited to 'src/util.c')
| -rw-r--r-- | src/util.c | 47 |
1 files changed, 42 insertions, 5 deletions
@@ -28,14 +28,46 @@ void color_print(FILE *stream, color_t *color) fprintf(stream, "#%02x%02x%02x%02x", r, g, b, a); } +const struct timespec timespec_from_ms(long ms) +{ + struct timespec ts = { + .tv_sec = ms / 1000, + .tv_nsec = (ms % 1000) * 1000000ul, + }; + return ts; +} + +const long timespec_to_ms(struct timespec ts) +{ + return (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000ul); +} + struct timespec timespec_diff(struct timespec a, struct timespec b) { - bool over = (b.tv_nsec - a.tv_nsec) < 0; - struct timespec diff = { - .tv_sec = b.tv_sec - a.tv_sec - over, - .tv_nsec = b.tv_nsec - a.tv_nsec + over * 1000000000ul, + bool over = (a.tv_nsec - b.tv_nsec) < 0; + struct timespec ts = { + .tv_sec = a.tv_sec - b.tv_sec - over, + .tv_nsec = a.tv_nsec - b.tv_nsec + over * 1000000000ul, }; - return diff; + return ts; +} + +struct timespec timespec_add(struct timespec a, struct timespec b) +{ + bool over = (a.tv_nsec + b.tv_nsec) > 1000000000ul; + struct timespec ts = { + .tv_sec = a.tv_sec + b.tv_sec + over, + .tv_nsec = a.tv_nsec + b.tv_nsec - over * 1000000000ul, + }; + return ts; +} + +struct timespec timespec_div(struct timespec ts, int n) +{ + ts.tv_nsec /= n; + ts.tv_nsec += ((ts.tv_sec % n) * 1000000000ul) / n; + ts.tv_sec /= n; + return ts; } bool timespec_greater(struct timespec a, struct timespec b) @@ -44,6 +76,11 @@ bool timespec_greater(struct timespec a, struct timespec b) || (a.tv_sec == b.tv_sec && a.tv_nsec > b.tv_nsec); } +bool timespec_zero(struct timespec ts) +{ + return ts.tv_sec == 0 && ts.tv_nsec == 0; +} + void timespec_print(FILE *stream, struct timespec *ts) { fprintf(stream, "%ld.%.9ld", ts->tv_sec, ts->tv_nsec); |
