Monado OpenXR Runtime
os_time.h
Go to the documentation of this file.
1 // Copyright 2019-2020, Collabora, Ltd.
2 // SPDX-License-Identifier: BSL-1.0
3 /*!
4  * @file
5  * @brief Wrapper around OS native time functions.
6  *
7  * These should be preferred over directly using native OS time functions in
8  * potentially-portable code. Additionally, in most cases these are preferred
9  * over timepoints from @ref time_state for general usage in drivers, etc.
10  *
11  * @author Drew DeVault <sir@cmpwn.com>
12  * @author Jakob Bornecrantz <jakob@collabora.com>
13  *
14  * @ingroup aux_os
15  */
16 
17 #pragma once
18 
19 #include "xrt/xrt_config_os.h"
20 #include "xrt/xrt_compiler.h"
21 
22 #ifdef XRT_OS_LINUX
23 #include <time.h>
24 #include <sys/time.h>
25 #define XRT_HAVE_TIMESPEC
26 #define XRT_HAVE_TIMEVAL
27 
28 #elif defined(XRT_DOXYGEN)
29 #include <time.h>
30 #define XRT_HAVE_TIMESPEC
31 #define XRT_HAVE_TIMEVAL
32 
33 #else
34 #error "No time support on non-Linux platforms yet."
35 #endif
36 
37 #ifdef __cplusplus
38 extern "C" {
39 #endif
40 
41 /*!
42  * @defgroup aux_os_time Portable Timekeeping
43  * @ingroup aux_os
44  *
45  * @brief Unifying wrapper around system time retrieval functions.
46  */
47 
48 
49 /*!
50  * @defgroup aux_os_time_extra Extra Timekeeping Utilities
51  * @ingroup aux_os_time
52  *
53  * @brief Less-portable utility functions for manipulating system time, for
54  * interoperation with platform APIs.
55  */
56 
57 
58 /*!
59  * @brief Sleep the given number of nanoseconds.
60  * @ingroup aux_os_time
61  */
62 static inline void
63 os_nanosleep(long nsec)
64 {
65 #ifdef XRT_OS_LINUX
66  struct timespec spec;
67  spec.tv_sec = 0;
68  spec.tv_nsec = nsec, nanosleep(&spec, NULL);
69 #endif
70 }
71 
72 #ifdef XRT_HAVE_TIMESPEC
73 /*!
74  * @brief Convert a timespec struct to nanoseconds.
75  * @ingroup aux_os_time_extra
76  */
77 static inline uint64_t
78 os_timespec_to_ns(struct timespec *spec)
79 {
80  uint64_t ns = 0;
81  ns += (uint64_t)spec->tv_sec * 1000 * 1000 * 1000;
82  ns += (uint64_t)spec->tv_nsec;
83  return ns;
84 }
85 #endif // XRT_HAVE_TIMESPEC
86 
87 
88 #ifdef XRT_HAVE_TIMEVAL
89 /*!
90  * @brief Convert a timeval struct to nanoseconds.
91  * @ingroup aux_os_time_extra
92  */
93 static inline uint64_t
94 os_timeval_to_ns(struct timeval *val)
95 {
96  uint64_t ns = 0;
97  ns += (uint64_t)val->tv_sec * 1000 * 1000 * 1000;
98  ns += (uint64_t)val->tv_usec * 1000;
99  return ns;
100 }
101 #endif // XRT_HAVE_TIMEVAL
102 
103 
104 /*!
105  * @brief Return a monotonic clock in nanoseconds.
106  * @ingroup aux_os_time
107  */
108 static inline uint64_t
109 os_monotonic_get_ns(void)
110 {
111 #ifdef XRT_OS_LINUX
112  struct timespec ts;
113  int ret = clock_gettime(CLOCK_MONOTONIC, &ts);
114  if (ret != 0) {
115  return 0;
116  }
117 
118  return os_timespec_to_ns(&ts);
119 #endif
120 }
121 
122 
123 #ifdef __cplusplus
124 }
125 #endif
Auto detect OS and certain features.
Header holding common defines.