Debian Codegraph @

src/bluetooth_data_tools/time.py

raw symbols SCIP
1 """Bluetooth time utils."""
2
3 from __future__ import annotations
4
5 import platform
6 import time
7 from collections.abc import Callable
8 from contextlib import suppress
9 from functools import partial
10
11 CLOCK_MONOTONIC_COARSE = 6
12
13
14 def __gen_monotonic_time_coarse() -> partial[float]:
15 """Return a function that provides monotonic time in seconds.
16
17 This is the coarse version of time_monotonic, which is faster but less accurate.
18
19 Since many arm64 and 32-bit platforms don't support VDSO with time.monotonic
20 because of errata, we can't rely on the kernel to provide a fast
21 monotonic time.
22
23 https://lore.kernel.org/lkml/[email protected]/
24 """
25 # We use a partial here since its implementation is in native code
26 # which allows us to avoid the overhead of the global lookup
27 # of CLOCK_MONOTONIC_COARSE.
28 return partial(time.clock_gettime, CLOCK_MONOTONIC_COARSE)
29
30
31 monotonic_time_coarse: Callable[[], float] = time.monotonic
32 _USE_COARSE_MONOTONIC_TIME = False
33
34 with suppress(Exception):
35 if (
36 platform.system() == "Linux"
37 and abs(time.monotonic() - __gen_monotonic_time_coarse()()) < 1
38 ):
39 monotonic_time_coarse = __gen_monotonic_time_coarse()
40 _USE_COARSE_MONOTONIC_TIME = True
41
42 if _USE_COARSE_MONOTONIC_TIME:
43 with suppress(ImportError):
44 from ._time_impl import ( # type: ignore[no-redef]
45 _monotonic_time_coarse as monotonic_time_coarse,
46 )
47
48
49 __all__ = [
50 "monotonic_time_coarse",
51 ]