timex.h
Go to the documentation of this file.
1 /*
2  * SPDX-FileCopyrightText: 2010 Kaspar Schleiser <kaspar@schleiser.de>
3  * SPDX-FileCopyrightText: 2014 Oliver Hahm <oliver.hahm@inria.fr>
4  * SPDX-License-Identifier: LGPL-2.1-only
5  */
6 
7 #pragma once
8 
19 #include <stdint.h>
20 #include <inttypes.h>
21 #include "time_units.h"
22 
23 #ifdef __cplusplus
24 extern "C" {
25 #endif
26 
30 #define TIMEX_MAX_STR_LEN (20)
31 /* 20 =
32  * + 10 byte: 2^32-1 for seconds
33  * + 1 byte: decimal point
34  * + 6 byte: microseconds (normalized)
35  * + 2 byte: " s" (unit)
36  * + 1 byte: '\0'
37  */
38 
45 typedef struct {
46  uint32_t seconds;
47  uint32_t microseconds;
48 } timex_t;
49 
58 timex_t timex_add(const timex_t a, const timex_t b);
59 
68 timex_t timex_sub(const timex_t a, const timex_t b);
69 
78 timex_t timex_set(uint32_t seconds, uint32_t microseconds);
79 
90 int timex_cmp(const timex_t a, const timex_t b);
91 
97 static inline void timex_normalize(timex_t *time)
98 {
99  time->seconds += (time->microseconds / US_PER_SEC);
100  time->microseconds %= US_PER_SEC;
101 }
102 
111 static inline int timex_isnormalized(const timex_t *time)
112 {
113  return (time->microseconds < US_PER_SEC);
114 }
115 
123 static inline uint64_t timex_uint64(const timex_t a)
124 {
125  return (uint64_t) a.seconds * US_PER_SEC + a.microseconds;
126 }
127 
135 static inline timex_t timex_from_uint64(const uint64_t timestamp)
136 {
137  return timex_set(timestamp / US_PER_SEC, timestamp % US_PER_SEC);
138 }
139 
152 const char *timex_to_str(timex_t t, char *timestamp);
153 
154 #ifdef __cplusplus
155 }
156 #endif
157 
#define US_PER_SEC
The number of microseconds per second.
Definition: time_units.h:81
timex_t timex_add(const timex_t a, const timex_t b)
Adds two timestamps.
int timex_cmp(const timex_t a, const timex_t b)
Compares two timex timestamps.
static void timex_normalize(timex_t *time)
Corrects timex structure so that microseconds < 1000000.
Definition: timex.h:97
const char * timex_to_str(timex_t t, char *timestamp)
Converts a timex timestamp to a string.
static int timex_isnormalized(const timex_t *time)
Tests a timex timestamp for normalization.
Definition: timex.h:111
timex_t timex_sub(const timex_t a, const timex_t b)
Subtracts two timestamps.
static uint64_t timex_uint64(const timex_t a)
Converts a timex timestamp to a 64 bit value.
Definition: timex.h:123
static timex_t timex_from_uint64(const uint64_t timestamp)
Converts a 64 bit value of microseconds to a timex timestamp.
Definition: timex.h:135
timex_t timex_set(uint32_t seconds, uint32_t microseconds)
Initializes a timex timestamp.
Adds include for missing inttype definitions.
A timex timestamp.
Definition: timex.h:45
uint32_t seconds
number of seconds
Definition: timex.h:46
uint32_t microseconds
number of microseconds
Definition: timex.h:47
Utility header providing time unit defines.