| 1 |
/* |
| 2 |
* Nanosecond Time Management |
| 3 |
* |
| 4 |
* This module provides time management utilities around the `nsec_t` type, |
| 5 |
* which carries time information encoded as nano-seconds since a |
| 6 |
* clock-specific EPOCH. The clock source is not encoded at all but must be |
| 7 |
* transferred via other means, if necessary. |
| 8 |
* |
| 9 |
* A 64-bit unsigned integer is used as backing data type. This can store |
| 10 |
* seconds up to: |
| 11 |
* |
| 12 |
* 2^64 / 1_000_000_000 = 18,446,744,073.7 |
| 13 |
* |
| 14 |
* or years up to: |
| 15 |
* |
| 16 |
* 2^64 / 1_000_000_000 / 60 / 60 / 24 / 365 ~= 584 |
| 17 |
* |
| 18 |
* This is a suitable range for time-keeping in most situations. If any |
| 19 |
* calendar, or other date-related functionality is needed, this type might not |
| 20 |
* be suitable. |
| 21 |
*/ |
| 22 |
|
| 23 |
#include <c-stdaux.h> |
| 24 |
#include <stdlib.h> |
| 25 |
#include <sys/time.h> |
| 26 |
#include <time.h> |
| 27 |
#include "util/nsec.h" |
| 28 |
|
| 29 |
#define NSEC_PER_SEC UINT64_C(1000000000) |
| 30 |
|
| 31 |
/* Similar to `intprops.h`: provides `_MAX` for signed types without it. */ |
| 32 |
#define NSEC_TIME_T_MAX \ |
| 33 |
((time_t)( \ |
| 34 |
(UINTMAX_C(1) << ((sizeof(time_t) << 3) - 1)) - 1) \ |
| 35 |
) |
| 36 |
|
| 37 |
/** |
| 38 |
* nsec_now() - get the current time in nanoseconds |
| 39 |
* @clock: clock to query |
| 40 |
* |
| 41 |
* Read the current time and return it in nanoseconds. The clock must be |
| 42 |
* specified by the caller. Only non-fallible clocks can be used with this |
| 43 |
* function. |
| 44 |
* |
| 45 |
* Return: the timestamp in nano seconds. |
| 46 |
*/ |
| 47 |
nsec_t nsec_now(clockid_t clock) { |
| 48 |
struct timespec ts; |
| 49 |
int r; |
| 50 |
|
| 51 |
r = clock_gettime(clock, &ts); |
| 52 |
c_assert(r >= 0); |
| 53 |
|
| 54 |
return (uint64_t)ts.tv_sec * NSEC_PER_SEC + (uint64_t)ts.tv_nsec; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* nsec_sleep() - pause execution |
| 59 |
* @clock: clock to use for time keeping |
| 60 |
* @until: absolute timeout of the pause |
| 61 |
* |
| 62 |
* Pause exeuction until the absolute timeout specified by `until` is reached. |
| 63 |
* The timeout must be relative to the clock specified by `clock`. |
| 64 |
* |
| 65 |
* The operation is automatically repeated, if it is interrupted by a signal. |
| 66 |
*/ |
| 67 |
void nsec_sleep(clockid_t clock, nsec_t until) { |
| 68 |
struct timespec ts; |
| 69 |
uint64_t tv_sec, tv_nsec; |
| 70 |
int r; |
| 71 |
|
| 72 |
tv_sec = until / NSEC_PER_SEC; |
| 73 |
tv_nsec = until % NSEC_PER_SEC; |
| 74 |
|
| 75 |
c_assert(tv_sec <= NSEC_TIME_T_MAX); |
| 76 |
|
| 77 |
ts.tv_sec = (time_t)tv_sec; |
| 78 |
ts.tv_nsec = (long)tv_nsec; |
| 79 |
|
| 80 |
do { |
| 81 |
/* Note that `clock_nanosleep()` does not use `errno`! */ |
| 82 |
r = clock_nanosleep(clock, TIMER_ABSTIME, &ts, NULL); |
| 83 |
c_assert(r == 0 || r == EINTR); |
| 84 |
} while (r == EINTR); |
| 85 |
} |