Monado OpenXR Runtime
u_wait.h
Go to the documentation of this file.
1// Copyright 2022, Collabora, Ltd.
2// Copyright 2024-2025, NVIDIA CORPORATION.
3// SPDX-License-Identifier: BSL-1.0
4/*!
5 * @file
6 * @brief Tiny file to implement precise waiting functions.
7 * @author Jakob Bornecrantz <jakob@collabora.com>
8 * @ingroup aux_util
9 */
10
11#pragma once
12
13#include "xrt/xrt_config_os.h"
14#include "os/os_time.h"
15
16#if defined(XRT_DOXYGEN)
17
18/*!
19 * OS specific tweak to wait time.
20 *
21 * @todo Measure on Windows.
22 * @ingroup aux_util
23 */
24#define U_WAIT_MEASURED_SCHEDULER_LATENCY_NS (uint64_t)(0)
25
26#elif defined(XRT_OS_LINUX) || defined(XRT_OS_ANDROID)
27#define U_WAIT_MEASURED_SCHEDULER_LATENCY_NS (uint64_t)(50 * 1000)
28#elif defined(XRT_OS_OSX)
29//! @TODO Measure
30#define U_WAIT_MEASURED_SCHEDULER_LATENCY_NS (uint64_t)(0)
31#elif defined(XRT_OS_WINDOWS)
32#define U_WAIT_MEASURED_SCHEDULER_LATENCY_NS (uint64_t)(0)
33#else
34#error "Unsupported platform!"
35#endif
36
37
38/*!
39 * Waits until the given time using the @ref os_precise_sleeper.
40 *
41 * @ingroup aux_util
42 */
43static inline void
44u_wait_until(struct os_precise_sleeper *sleeper, uint64_t until_ns)
45{
46 uint64_t now_ns = os_monotonic_get_ns();
47
48 // Lets hope its not to late.
49 bool fuzzy_in_the_past = time_is_less_then_or_within_range(until_ns, now_ns, U_TIME_1MS_IN_NS);
50
51 // When we should wake up is in the past:ish.
52 if (fuzzy_in_the_past) {
53 return;
54 }
55
56 // Sufficiently in the future.
57 uint32_t delay = (uint32_t)(until_ns - now_ns - U_WAIT_MEASURED_SCHEDULER_LATENCY_NS);
58 os_precise_sleeper_nanosleep(sleeper, delay);
59}
static int64_t os_monotonic_get_ns(void)
Return a monotonic clock in nanoseconds.
Definition: os_time.h:319
static bool time_is_less_then_or_within_range(timepoint_ns a, timepoint_ns b, int64_t range)
Fuzzy comparisons.
Definition: u_time.h:171
static void u_wait_until(struct os_precise_sleeper *sleeper, uint64_t until_ns)
Waits until the given time using the os_precise_sleeper.
Definition: u_wait.h:44
#define U_WAIT_MEASURED_SCHEDULER_LATENCY_NS
OS specific tweak to wait time.
Definition: u_wait.h:24
Wrapper around OS native time functions.
Definition: os_time.h:219
static void os_precise_sleeper_nanosleep(struct os_precise_sleeper *ops, int32_t nsec)
Sleep the given number of nanoseconds, trying harder to be precise.
Definition: os_time.h:247
#define U_TIME_1MS_IN_NS
The number of nanoseconds in a millisecond.
Definition: u_time.h:54
Auto detect OS and certain features.