timer/timespec.c
2024-06-23 23:20:44 -05:00

49 lines
1.1 KiB
C

#include <time.h>
#include <stdio.h>
#include <assert.h>
#include <stdint.h>
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_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);
}
int64_t rem = c.tv_sec % length;
c.tv_sec /= length;
c.tv_nsec = (c.tv_nsec / length) + (rem * 1000000000 / length);
assert(c.tv_nsec < 1000000000);
//printf("average: %ld.%09ld\n", c.tv_sec, c.tv_nsec);
return c;
}