2 * copyright (c) 2012 Emil Mikulic.
4 * now.c: a cache of the current time.
6 * Permission to use, copy, modify, and distribute this file for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
25 static struct timespec clock_real
, clock_mono
;
26 static int now_initialized
= 0;
29 assert(now_initialized
);
30 return clock_real
.tv_sec
;
34 assert(now_initialized
);
35 return clock_mono
.tv_sec
;
38 static int before(const struct timespec
*a
, const struct timespec
*b
) {
39 if (a
->tv_sec
< b
->tv_sec
)
41 if (a
->tv_sec
== b
->tv_sec
&& a
->tv_nsec
< b
->tv_nsec
)
46 static void clock_update(const clockid_t clk_id
,
47 struct timespec
*dest
,
51 clock_gettime(clk_id
, &t
);
52 if (now_initialized
&& before(&t
, dest
)) {
53 verbosef("%s clock went backwards from %ld.%09ld to %ld.%09ld",
60 memcpy(dest
, &t
, sizeof(t
));
63 static void all_clocks_update(void) {
64 clock_update(CLOCK_REALTIME
, &clock_real
, "realtime");
65 clock_update(CLOCK_MONOTONIC
, &clock_mono
, "monotonic");
69 assert(!now_initialized
);
74 void now_update(void) {
75 assert(now_initialized
);
79 long mono_to_real(const long t
) {
80 assert(now_initialized
);
81 return t
- clock_mono
.tv_sec
+ clock_real
.tv_sec
;
84 long real_to_mono(const long t
) {
85 assert(now_initialized
);
86 return t
- clock_real
.tv_sec
+ clock_mono
.tv_sec
;
89 /* vim:set ts=3 sw=3 tw=80 et: */