]> git.proxmox.com Git - mirror_frr.git/blob - lib/monotime.h
7bd338649830901ebb713592174f5ef9adf5d06e
[mirror_frr.git] / lib / monotime.h
1 /*
2 * Copyright (c) 2017 David Lamparter, for NetDEF, Inc.
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17 #ifndef _FRR_MONOTIME_H
18 #define _FRR_MONOTIME_H
19
20 #include <stdint.h>
21 #include <time.h>
22 #include <sys/time.h>
23
24 #ifndef TIMESPEC_TO_TIMEVAL
25 /* should be in sys/time.h on BSD & Linux libcs */
26 #define TIMESPEC_TO_TIMEVAL(tv, ts) \
27 do { \
28 (tv)->tv_sec = (ts)->tv_sec; \
29 (tv)->tv_usec = (ts)->tv_nsec / 1000; \
30 } while (0)
31 #endif
32 #ifndef TIMEVAL_TO_TIMESPEC
33 /* should be in sys/time.h on BSD & Linux libcs */
34 #define TIMEVAL_TO_TIMESPEC(tv, ts) \
35 do { \
36 (ts)->tv_sec = (tv)->tv_sec; \
37 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
38 } while (0)
39 #endif
40
41 static inline time_t monotime(struct timeval *tvo)
42 {
43 struct timespec ts;
44
45 clock_gettime(CLOCK_MONOTONIC, &ts);
46 if (tvo) {
47 TIMESPEC_TO_TIMEVAL(tvo, &ts);
48 }
49 return ts.tv_sec;
50 }
51
52 /* the following two return microseconds, not time_t!
53 *
54 * also, they're negative forms of each other, but having both makes the
55 * code more readable
56 */
57 static inline int64_t monotime_since(const struct timeval *ref,
58 struct timeval *out)
59 {
60 struct timeval tv;
61 monotime(&tv);
62 timersub(&tv, ref, &tv);
63 if (out)
64 *out = tv;
65 return (int64_t)tv.tv_sec * 1000000LL + tv.tv_usec;
66 }
67
68 static inline int64_t monotime_until(const struct timeval *ref,
69 struct timeval *out)
70 {
71 struct timeval tv;
72 monotime(&tv);
73 timersub(ref, &tv, &tv);
74 if (out)
75 *out = tv;
76 return (int64_t)tv.tv_sec * 1000000LL + tv.tv_usec;
77 }
78
79 #endif /* _FRR_MONOTIME_H */