#include #include #include #include struct timespec timespec_sub(const struct timespec * a, const struct timespec * b) { struct timespec c = { .tv_sec = a->tv_sec - b->tv_sec, .tv_nsec = a->tv_nsec - b->tv_nsec }; if (c.tv_nsec < 0) { c.tv_nsec += 1000000000; c.tv_sec -= 1; } return c; } struct timespec timespec_add(const struct timespec * a, const struct timespec * b) { struct timespec c = { .tv_sec = a->tv_sec + b->tv_sec, .tv_nsec = a->tv_nsec + b->tv_nsec }; int64_t rem = c.tv_nsec / 1000000000; c.tv_nsec = c.tv_nsec % 1000000000; c.tv_sec += rem; return c; } struct timespec timespec_div(const struct timespec * a, int n) { int64_t rem = a->tv_sec % n; struct timespec c = { .tv_sec = a->tv_sec / n, .tv_nsec = (a->tv_nsec / n) + (rem * 1000000000 / n) }; assert(c.tv_nsec < 1000000000); return c; } struct timespec timespec_average(const struct timespec * ts, int length) { struct timespec c = {0}; for (int i = 0; i < length; i++) { c = timespec_add(&c, &ts[i]); //printf("rtt[%d]: %ld.%09ld\n", i, ts[i].tv_sec, ts[i].tv_nsec); } struct timespec d = timespec_div(&c, length); //printf("average: %ld.%09ld\n", d.tv_sec, d.tv_nsec); return d; }