timer/timespec.h
2024-06-23 18:28:05 -05:00

51 lines
1.3 KiB
C

#pragma once
#include <time.h>
#include <stdio.h>
#include <assert.h>
#include <stdint.h>
static struct timespec diff_timespec(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;
}
static struct timespec add_timespec(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;
}
static struct timespec average_timespec(const struct timespec * ts,
int length)
{
struct timespec c = {0};
for (int i = 0; i < length; i++) {
c = add_timespec(&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;
}