Skip to content

Instantly share code, notes, and snippets.

@rikusalminen
Created August 25, 2011 16:05
Show Gist options
  • Save rikusalminen/1171039 to your computer and use it in GitHub Desktop.
Save rikusalminen/1171039 to your computer and use it in GitHub Desktop.
timespec arithmetic
#define NS_IN_SEC 1000000000
// I bet there's a subtle overflow bug somewhere here
static inline struct timespec timespec_add(const struct timespec * restrict a, const struct timespec * restrict b)
{
unsigned long nsecs = (a->tv_nsec % NS_IN_SEC) + (b->tv_nsec % NS_IN_SEC);
struct timespec result = {
a->tv_sec + b->tv_sec + (a->tv_nsec / NS_IN_SEC) + (b->tv_nsec / NS_IN_SEC) + (nsecs / NS_IN_SEC),
nsecs % NS_IN_SEC
};
return result;
}
static inline struct timespec timespec_diff(const struct timespec * restrict a, const struct timespec * restrict b)
{
if(a->tv_nsec < b->tv_nsec)
{
struct timespec result = {
a->tv_sec - b->tv_sec - 1,
NS_IN_SEC + a->tv_nsec - b->tv_nsec,
};
return result;
} else
{
struct timespec result = {
a->tv_sec - b->tv_sec,
a->tv_nsec - b->tv_nsec,
};
return result;
}
}
static inline struct timespec timespec_mad(const struct timespec * restrict a, const struct timespec * restrict b, uint64_t c)
{
// TODO: replace this with something close to O(1)
struct timespec result = *a;
for(uint64_t i = 0; i < c; ++i)
result = timespec_add(&result, b);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment