d45457bf5295424e9c904b6caa8aa3d702a358fa
[detour.git] / common.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <jh.h>
4 #include <unistd.h>
5 #include <time.h>
6 #include <assert.h>
7
8 time_t real_seconds(void) {
9   struct timespec t;
10   int s = clock_gettime(CLOCK_REALTIME, &t);
11   assert(s==0);
12   return t.tv_sec;
13 }
14
15 /* Subtract the `struct timeval' values X and Y,
16    storing the result in RESULT.
17    Return 1 if the difference is negative, otherwise 0. */
18 int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y) {
19   /* Perform the carry for the later subtraction by updating y. */
20   if (x->tv_usec < y->tv_usec) {
21     int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
22     y->tv_usec -= 1000000 * nsec;
23     y->tv_sec += nsec;
24   }
25   if (x->tv_usec - y->tv_usec > 1000000) {
26     int nsec = (x->tv_usec - y->tv_usec) / 1000000;
27     y->tv_usec += 1000000 * nsec;
28     y->tv_sec -= nsec;
29   }
30
31   /* Compute the time remaining to wait.
32      tv_usec is certainly positive. */
33   result->tv_sec = x->tv_sec - y->tv_sec;
34   result->tv_usec = x->tv_usec - y->tv_usec;
35
36   /* Return 1 if result is negative. */
37   return x->tv_sec < y->tv_sec;
38 }
39
40 void sleep_until(time_t dst_sec) {
41   struct timespec dst;
42   dst.tv_sec = dst_sec;
43   dst.tv_nsec = 0;
44   while (clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &dst, NULL)) /* nothing */;
45 }
46
47 time_t round_up(time_t t, int align) {
48   t = t - 1; /* counter bad +t for aligned things in last step */
49   t = t - t%align; /* round down to align */
50   t = t + align; /* add alignment to make it a round up */
51   return t;
52 }