xref: /aosp_15_r20/external/pigweed/pw_chrono/docs.rst (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1*61c4878aSAndroid Build Coastguard Worker.. _module-pw_chrono:
2*61c4878aSAndroid Build Coastguard Worker
3*61c4878aSAndroid Build Coastguard Worker=========
4*61c4878aSAndroid Build Coastguard Workerpw_chrono
5*61c4878aSAndroid Build Coastguard Worker=========
6*61c4878aSAndroid Build Coastguard Worker.. pigweed-module::
7*61c4878aSAndroid Build Coastguard Worker   :name: pw_chrono
8*61c4878aSAndroid Build Coastguard Worker
9*61c4878aSAndroid Build Coastguard WorkerPigweed's chrono module provides facilities for applications to deal with time,
10*61c4878aSAndroid Build Coastguard Workerleveraging many pieces of STL's the ``std::chrono`` library but with a focus
11*61c4878aSAndroid Build Coastguard Workeron portability for constrained embedded devices and maintaining correctness.
12*61c4878aSAndroid Build Coastguard Worker
13*61c4878aSAndroid Build Coastguard Worker-------------------------------
14*61c4878aSAndroid Build Coastguard Worker``duration`` and ``time_point``
15*61c4878aSAndroid Build Coastguard Worker-------------------------------
16*61c4878aSAndroid Build Coastguard WorkerPigweed's time primitives rely on C++'s
17*61c4878aSAndroid Build Coastguard Worker`<chrono> <https://en.cppreference.com/w/cpp/header/chrono>`_ library to enable
18*61c4878aSAndroid Build Coastguard Workerusers to express intents with strongly typed real time units through
19*61c4878aSAndroid Build Coastguard Worker`std::chrono::duration <https://en.cppreference.com/w/cpp/chrono/duration>`_
20*61c4878aSAndroid Build Coastguard Workerand
21*61c4878aSAndroid Build Coastguard Worker`std::chrono::time_point <https://en.cppreference.com/w/cpp/chrono/time_point>`_
22*61c4878aSAndroid Build Coastguard Worker.
23*61c4878aSAndroid Build Coastguard Worker
24*61c4878aSAndroid Build Coastguard WorkerWhat are they?
25*61c4878aSAndroid Build Coastguard Worker==============
26*61c4878aSAndroid Build Coastguard WorkerAt a high level, durations and time_points at run time are tick counts which
27*61c4878aSAndroid Build Coastguard Workerare wrapped in templated metadata which is only used at compile time.
28*61c4878aSAndroid Build Coastguard Worker
29*61c4878aSAndroid Build Coastguard WorkerThe STL's
30*61c4878aSAndroid Build Coastguard Worker`std::chrono::duration <https://en.cppreference.com/w/cpp/chrono/duration>`_
31*61c4878aSAndroid Build Coastguard Workerclass template represents a time interval. It consists of a count of ticks of
32*61c4878aSAndroid Build Coastguard Workertype ``rep`` and a tick ``period``, where the tick period is a ``std::ratio``
33*61c4878aSAndroid Build Coastguard Workerrepresenting the time in seconds from one tick to the next.
34*61c4878aSAndroid Build Coastguard Worker
35*61c4878aSAndroid Build Coastguard WorkerThe only data stored in a duration is a tick count of type ``rep``. The
36*61c4878aSAndroid Build Coastguard Worker``period`` is included as part of the duration's type, and is only used when
37*61c4878aSAndroid Build Coastguard Workerconverting between different durations.
38*61c4878aSAndroid Build Coastguard Worker
39*61c4878aSAndroid Build Coastguard WorkerSimilarly, the STL's
40*61c4878aSAndroid Build Coastguard Worker`std::chrono::time_point <https://en.cppreference.com/w/cpp/chrono/time_point>`_
41*61c4878aSAndroid Build Coastguard Workerclass template represents a point in time (i.e. timestamp). It consists of a
42*61c4878aSAndroid Build Coastguard Workervalue of type ``duration`` which represents the time interval from the start of
43*61c4878aSAndroid Build Coastguard Workerthe ``clock``'s epoch.
44*61c4878aSAndroid Build Coastguard Worker
45*61c4878aSAndroid Build Coastguard WorkerThe ``duration`` and ``time_point`` class templates can be represented with the
46*61c4878aSAndroid Build Coastguard Workerfollowing simplified model, ignoring most of their member functions:
47*61c4878aSAndroid Build Coastguard Worker
48*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp
49*61c4878aSAndroid Build Coastguard Worker
50*61c4878aSAndroid Build Coastguard Worker   namespace std::chrono {
51*61c4878aSAndroid Build Coastguard Worker
52*61c4878aSAndroid Build Coastguard Worker   template<class Rep, class Period = std::ratio<1, 1>>
53*61c4878aSAndroid Build Coastguard Worker   class duration {
54*61c4878aSAndroid Build Coastguard Worker    public:
55*61c4878aSAndroid Build Coastguard Worker     using rep = Rep;
56*61c4878aSAndroid Build Coastguard Worker     using period = Period;
57*61c4878aSAndroid Build Coastguard Worker
58*61c4878aSAndroid Build Coastguard Worker     constexpr rep count() const { return tick_count_; }
59*61c4878aSAndroid Build Coastguard Worker
60*61c4878aSAndroid Build Coastguard Worker     static constexpr duration zero() noexcept {
61*61c4878aSAndroid Build Coastguard Worker       return duration(0);
62*61c4878aSAndroid Build Coastguard Worker     }
63*61c4878aSAndroid Build Coastguard Worker
64*61c4878aSAndroid Build Coastguard Worker     // Other member functions...
65*61c4878aSAndroid Build Coastguard Worker
66*61c4878aSAndroid Build Coastguard Worker    private:
67*61c4878aSAndroid Build Coastguard Worker     rep tick_count_;
68*61c4878aSAndroid Build Coastguard Worker   };
69*61c4878aSAndroid Build Coastguard Worker
70*61c4878aSAndroid Build Coastguard Worker   template<class Clock, class Duration = typename Clock::duration>
71*61c4878aSAndroid Build Coastguard Worker   class time_point {
72*61c4878aSAndroid Build Coastguard Worker    public:
73*61c4878aSAndroid Build Coastguard Worker     using duration = Duration;
74*61c4878aSAndroid Build Coastguard Worker     using rep = Duration::rep;
75*61c4878aSAndroid Build Coastguard Worker     using period = Duration::period;
76*61c4878aSAndroid Build Coastguard Worker     using clock = Clock;
77*61c4878aSAndroid Build Coastguard Worker
78*61c4878aSAndroid Build Coastguard Worker     constexpr duration time_since_epoch() const { return time_since_epoch_; }
79*61c4878aSAndroid Build Coastguard Worker
80*61c4878aSAndroid Build Coastguard Worker     // Other member functions...
81*61c4878aSAndroid Build Coastguard Worker
82*61c4878aSAndroid Build Coastguard Worker    private:
83*61c4878aSAndroid Build Coastguard Worker     duration time_since_epoch_;
84*61c4878aSAndroid Build Coastguard Worker   };
85*61c4878aSAndroid Build Coastguard Worker
86*61c4878aSAndroid Build Coastguard Worker  }  // namespace std::chrono
87*61c4878aSAndroid Build Coastguard Worker
88*61c4878aSAndroid Build Coastguard WorkerWhat ``rep`` type should be used?
89*61c4878aSAndroid Build Coastguard Worker=================================
90*61c4878aSAndroid Build Coastguard WorkerThe duration's ``rep``, or tick count type, can be a floating point or a signed
91*61c4878aSAndroid Build Coastguard Workerinteger. For most applications, this is a signed integer just as how one may
92*61c4878aSAndroid Build Coastguard Workerrepresent the number of ticks for an RTOS API or the number of nanoseconds in
93*61c4878aSAndroid Build Coastguard WorkerPOSIX.
94*61c4878aSAndroid Build Coastguard Worker
95*61c4878aSAndroid Build Coastguard WorkerThe ``rep`` should be able to represent the durations of time necessary for the
96*61c4878aSAndroid Build Coastguard Workerapplication. When possible, use ``int64_t`` as the ``rep`` for a clock's
97*61c4878aSAndroid Build Coastguard Workerduration in order to trivially avoid integer underflow and overflow risks by
98*61c4878aSAndroid Build Coastguard Workercovering a range of at least ±292 years. This matches the STL's requirements
99*61c4878aSAndroid Build Coastguard Workerfor the duration helper types which are relevant for a clock's tick period:
100*61c4878aSAndroid Build Coastguard Worker
101*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::nanoseconds  duration</*signed integer type of at least 64 bits*/, std::nano>``
102*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::microseconds duration</*signed integer type of at least 55 bits*/, std::micro>``
103*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::milliseconds duration</*signed integer type of at least 45 bits*/, std::milli>``
104*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::seconds  duration</*signed integer type of at least 35 bits*/>``
105*61c4878aSAndroid Build Coastguard Worker
106*61c4878aSAndroid Build Coastguard WorkerWith this guidance one can avoid common pitfalls like ``uint32_t`` millisecond
107*61c4878aSAndroid Build Coastguard Workertick rollover bugs when using RTOSes every 49.7 days.
108*61c4878aSAndroid Build Coastguard Worker
109*61c4878aSAndroid Build Coastguard Worker.. warning::
110*61c4878aSAndroid Build Coastguard Worker   Avoid the ``duration<>::min()`` and ``duration<>::max()`` helper member
111*61c4878aSAndroid Build Coastguard Worker   functions where possible as they exceed the ±292 years duration limit
112*61c4878aSAndroid Build Coastguard Worker   assumption. There's an immediate risk of integer underflow or overflow for
113*61c4878aSAndroid Build Coastguard Worker   any arithmetic operations. Consider using ``std::optional`` instead of
114*61c4878aSAndroid Build Coastguard Worker   priming a variable with a value at the limit.
115*61c4878aSAndroid Build Coastguard Worker
116*61c4878aSAndroid Build Coastguard WorkerHelper duration types and literals
117*61c4878aSAndroid Build Coastguard Worker==================================
118*61c4878aSAndroid Build Coastguard WorkerThe STL's ``<chrono>`` library includes a set of helper types based on actual
119*61c4878aSAndroid Build Coastguard Workertime units, including the following (and more):
120*61c4878aSAndroid Build Coastguard Worker
121*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::nanoseconds``
122*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::microseconds``
123*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::milliseconds``
124*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::seconds``
125*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::minutes``
126*61c4878aSAndroid Build Coastguard Worker* ``std::chrono::hours``
127*61c4878aSAndroid Build Coastguard Worker
128*61c4878aSAndroid Build Coastguard WorkerAs an example you can use these as follows:
129*61c4878aSAndroid Build Coastguard Worker
130*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp
131*61c4878aSAndroid Build Coastguard Worker
132*61c4878aSAndroid Build Coastguard Worker   #include <chrono>
133*61c4878aSAndroid Build Coastguard Worker
134*61c4878aSAndroid Build Coastguard Worker   void Foo() {
135*61c4878aSAndroid Build Coastguard Worker     Bar(std::chrono::milliseconds(42));
136*61c4878aSAndroid Build Coastguard Worker   }
137*61c4878aSAndroid Build Coastguard Worker
138*61c4878aSAndroid Build Coastguard WorkerIn addition, the inline namespace ``std::literals::chrono_literals`` includes:
139*61c4878aSAndroid Build Coastguard Worker
140*61c4878aSAndroid Build Coastguard Worker* ``operator""ns`` for ``std::chrono::nanoseconds``
141*61c4878aSAndroid Build Coastguard Worker* ``operator""us`` for ``std::chrono::microseconds``
142*61c4878aSAndroid Build Coastguard Worker* ``operator""ms`` for ``std::chrono::milliseconds``
143*61c4878aSAndroid Build Coastguard Worker* ``operator""s`` for ``std::chrono::seconds``
144*61c4878aSAndroid Build Coastguard Worker* ``operator""min`` for ``std::chrono::minutes``
145*61c4878aSAndroid Build Coastguard Worker* ``operator""h`` for ``std::chrono::hours``
146*61c4878aSAndroid Build Coastguard Worker
147*61c4878aSAndroid Build Coastguard WorkerAs an example you can use these as follows:
148*61c4878aSAndroid Build Coastguard Worker
149*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp
150*61c4878aSAndroid Build Coastguard Worker
151*61c4878aSAndroid Build Coastguard Worker   using std::literals::chrono_literals::ms;
152*61c4878aSAndroid Build Coastguard Worker   // Or if you want them all: using namespace std::chrono_literals;
153*61c4878aSAndroid Build Coastguard Worker
154*61c4878aSAndroid Build Coastguard Worker   void Foo() {
155*61c4878aSAndroid Build Coastguard Worker     Bar(42ms);
156*61c4878aSAndroid Build Coastguard Worker   }
157*61c4878aSAndroid Build Coastguard Worker
158*61c4878aSAndroid Build Coastguard WorkerFor these helper duration types to be compatible with API's that take a
159*61c4878aSAndroid Build Coastguard Worker`SystemClock::duration` either an :ref:`implicit<Implicit lossless conversions>`
160*61c4878aSAndroid Build Coastguard Workeror :ref:`explicit lossy<Explicit lossy conversions>` conversion must be done.
161*61c4878aSAndroid Build Coastguard Worker
162*61c4878aSAndroid Build Coastguard WorkerConverting between time units and clock durations
163*61c4878aSAndroid Build Coastguard Worker=================================================
164*61c4878aSAndroid Build Coastguard WorkerSo why go through all of this trouble instead of just using ticks or instead
165*61c4878aSAndroid Build Coastguard Workerjust using one time unit such as nanoseconds? For example, imagine that you have
166*61c4878aSAndroid Build Coastguard Workera 1kHz RTOS tick period and you would like to express a timeout duration:
167*61c4878aSAndroid Build Coastguard Worker
168*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp
169*61c4878aSAndroid Build Coastguard Worker
170*61c4878aSAndroid Build Coastguard Worker   // Instead of using ticks which are not portable between RTOS configurations,
171*61c4878aSAndroid Build Coastguard Worker   // as the tick period may be different:
172*61c4878aSAndroid Build Coastguard Worker   constexpr uint32_t kFooNotificationTimeoutTicks = 42;
173*61c4878aSAndroid Build Coastguard Worker   bool TryGetNotificationFor(uint32_t ticks);
174*61c4878aSAndroid Build Coastguard Worker
175*61c4878aSAndroid Build Coastguard Worker   // And instead of using a time unit which is prone to accidental conversion
176*61c4878aSAndroid Build Coastguard Worker   // errors as all variables must maintain the time units:
177*61c4878aSAndroid Build Coastguard Worker   constexpr uint32_t kFooNotificationTimeoutMs = 42;
178*61c4878aSAndroid Build Coastguard Worker   bool TryGetNotificationFor(uint32_t milliseconds);
179*61c4878aSAndroid Build Coastguard Worker
180*61c4878aSAndroid Build Coastguard Worker   // We can instead use a defined clock and its duration for the kernel and rely
181*61c4878aSAndroid Build Coastguard Worker   // on implicit lossless conversions:
182*61c4878aSAndroid Build Coastguard Worker   #include <chrono>
183*61c4878aSAndroid Build Coastguard Worker   #include "pw_chrono/system_clock.h"
184*61c4878aSAndroid Build Coastguard Worker   constexpr SystemClock::duration kFooNotificationTimeout =
185*61c4878aSAndroid Build Coastguard Worker       std::chrono::milliseconds(42);
186*61c4878aSAndroid Build Coastguard Worker   bool TryGetNotificationFor(SystemClock::duration timeout);
187*61c4878aSAndroid Build Coastguard Worker
188*61c4878aSAndroid Build Coastguard Worker   void MaybeProcessNotification() {
189*61c4878aSAndroid Build Coastguard Worker     if (TryGetNotificationFor(kFooNotificationTimeout)) {
190*61c4878aSAndroid Build Coastguard Worker       ProcessNotification();
191*61c4878aSAndroid Build Coastguard Worker     }
192*61c4878aSAndroid Build Coastguard Worker   }
193*61c4878aSAndroid Build Coastguard Worker
194*61c4878aSAndroid Build Coastguard Worker.. _Implicit lossless conversions:
195*61c4878aSAndroid Build Coastguard Worker
196*61c4878aSAndroid Build Coastguard WorkerImplicit lossless conversions
197*61c4878aSAndroid Build Coastguard Worker-----------------------------
198*61c4878aSAndroid Build Coastguard WorkerWait, but how does this work? Is there a hidden cost? The ``duration`` type
199*61c4878aSAndroid Build Coastguard Workercomes with built in implicit lossless conversion support which is evaluated at
200*61c4878aSAndroid Build Coastguard Workercompile time where possible.
201*61c4878aSAndroid Build Coastguard Worker
202*61c4878aSAndroid Build Coastguard WorkerIf you rely on implicit conversions then the worst case cost is multiplication,
203*61c4878aSAndroid Build Coastguard Workerthere is no risk of a division operation.
204*61c4878aSAndroid Build Coastguard Worker
205*61c4878aSAndroid Build Coastguard WorkerIf the implicit conversion cannot be guaranteed at compile time to be lossless
206*61c4878aSAndroid Build Coastguard Workerfor all possible tick count values, then it will fail to compile.
207*61c4878aSAndroid Build Coastguard Worker
208*61c4878aSAndroid Build Coastguard WorkerAs an example you can always convert from ``std::chrono::seconds`` to
209*61c4878aSAndroid Build Coastguard Worker``std::chrono::milliseconds`` in a lossless manner. However, you cannot
210*61c4878aSAndroid Build Coastguard Workerguarantee for all tick count values that ``std::chrono::milliseconds`` can be
211*61c4878aSAndroid Build Coastguard Workerlosslessly converted to ``std::chrono::seconds``, even though it may work for
212*61c4878aSAndroid Build Coastguard Workersome values like ``0``, ``1000``, etc.
213*61c4878aSAndroid Build Coastguard Worker
214*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp
215*61c4878aSAndroid Build Coastguard Worker
216*61c4878aSAndroid Build Coastguard Worker   #include <chrono>
217*61c4878aSAndroid Build Coastguard Worker
218*61c4878aSAndroid Build Coastguard Worker   constexpr std::chrono::milliseconds this_compiles =
219*61c4878aSAndroid Build Coastguard Worker       std::chrono::seconds(42);
220*61c4878aSAndroid Build Coastguard Worker
221*61c4878aSAndroid Build Coastguard Worker   // This cannot compile, because for some duration values it is lossy even
222*61c4878aSAndroid Build Coastguard Worker   // though this particular value can be in theory converted to whole seconds.
223*61c4878aSAndroid Build Coastguard Worker   // constexpr std::chrono::seconds this_does_not_compile =
224*61c4878aSAndroid Build Coastguard Worker   //    std::chrono::milliseconds(1000);
225*61c4878aSAndroid Build Coastguard Worker
226*61c4878aSAndroid Build Coastguard Worker.. _Explicit lossy conversions:
227*61c4878aSAndroid Build Coastguard Worker
228*61c4878aSAndroid Build Coastguard WorkerExplicit lossy conversions
229*61c4878aSAndroid Build Coastguard Worker--------------------------
230*61c4878aSAndroid Build Coastguard WorkerWhile code should prefer implicit lossless conversions whenever possible,
231*61c4878aSAndroid Build Coastguard Workersometimes a lossy conversion is required.
232*61c4878aSAndroid Build Coastguard Worker
233*61c4878aSAndroid Build Coastguard WorkerConsider an example where a RTOS employs a 128Hz tick clock. The 128Hz
234*61c4878aSAndroid Build Coastguard Worker``period`` can be perfectly represented with a ``std::ratio<1,128>``. However
235*61c4878aSAndroid Build Coastguard Workeryou will not be able to implicitly convert any real time unit durations to this
236*61c4878aSAndroid Build Coastguard Workerduration type. Instead explicit lossy conversions must be used. Pigweed
237*61c4878aSAndroid Build Coastguard Workerrecommends explicitly using:
238*61c4878aSAndroid Build Coastguard Worker
239*61c4878aSAndroid Build Coastguard Worker* `std::chrono::floor <https://en.cppreference.com/w/cpp/chrono/duration/floor>`_
240*61c4878aSAndroid Build Coastguard Worker  to round down.
241*61c4878aSAndroid Build Coastguard Worker* `std::chrono::round <https://en.cppreference.com/w/cpp/chrono/duration/round>`_
242*61c4878aSAndroid Build Coastguard Worker  to round to the nearest, rounding to even in halfway cases.
243*61c4878aSAndroid Build Coastguard Worker* `std::chrono::ceil <https://en.cppreference.com/w/cpp/chrono/duration/ceil>`_
244*61c4878aSAndroid Build Coastguard Worker  to round up.
245*61c4878aSAndroid Build Coastguard Worker* `pw::chrono::SystemClock::for_at_least` to round up using the `SystemClock::period`,
246*61c4878aSAndroid Build Coastguard Worker  as a more explicit form of std::chrono::ceil.
247*61c4878aSAndroid Build Coastguard Worker
248*61c4878aSAndroid Build Coastguard Worker.. Note::
249*61c4878aSAndroid Build Coastguard Worker   Pigweed does not recommend using ``std::chrono::duration_cast<>`` which
250*61c4878aSAndroid Build Coastguard Worker   truncates dowards zero like ``static_cast``. This is typically not the desired
251*61c4878aSAndroid Build Coastguard Worker   rounding behavior when dealing with time units. Instead, where possible we
252*61c4878aSAndroid Build Coastguard Worker   recommend the more explicit, self-documenting ``std::chrono::floor``,
253*61c4878aSAndroid Build Coastguard Worker   ``std::chrono::round``, and ``std::chrono::ceil``.
254*61c4878aSAndroid Build Coastguard Worker
255*61c4878aSAndroid Build Coastguard WorkerNow knowing this, the previous example could be portably and correctly handled
256*61c4878aSAndroid Build Coastguard Workeras follows:
257*61c4878aSAndroid Build Coastguard Worker
258*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp
259*61c4878aSAndroid Build Coastguard Worker
260*61c4878aSAndroid Build Coastguard Worker   #include <chrono>
261*61c4878aSAndroid Build Coastguard Worker
262*61c4878aSAndroid Build Coastguard Worker   #include "pw_chrono/system_clock.h"
263*61c4878aSAndroid Build Coastguard Worker
264*61c4878aSAndroid Build Coastguard Worker   // We want to round up to ensure we block for at least the specified duration,
265*61c4878aSAndroid Build Coastguard Worker   // instead of rounding down. Imagine for example the extreme case where you
266*61c4878aSAndroid Build Coastguard Worker   // may round down to zero or one, you would definitely want to at least block.
267*61c4878aSAndroid Build Coastguard Worker   constexpr SystemClock::duration kFooNotificationTimeout =
268*61c4878aSAndroid Build Coastguard Worker       std::chrono::ceil(std::chrono::milliseconds(42));
269*61c4878aSAndroid Build Coastguard Worker   bool TryGetNotificationFor(SystemClock::duration timeout);
270*61c4878aSAndroid Build Coastguard Worker
271*61c4878aSAndroid Build Coastguard Worker   void MaybeProcessNotification() {
272*61c4878aSAndroid Build Coastguard Worker     if (TryGetNotificationFor(kFooNotificationTimeout)) {
273*61c4878aSAndroid Build Coastguard Worker       ProcessNotification();
274*61c4878aSAndroid Build Coastguard Worker     }
275*61c4878aSAndroid Build Coastguard Worker   }
276*61c4878aSAndroid Build Coastguard Worker
277*61c4878aSAndroid Build Coastguard WorkerThis code is lossless if the clock period is 1kHz and it's correct using a
278*61c4878aSAndroid Build Coastguard Workerdivision which rounds up when the clock period is 128Hz.
279*61c4878aSAndroid Build Coastguard Worker
280*61c4878aSAndroid Build Coastguard Worker.. Note::
281*61c4878aSAndroid Build Coastguard Worker   When using ``pw::chrono::SystemClock::duration`` for timeouts, prefer
282*61c4878aSAndroid Build Coastguard Worker   using its ``SystemClock::for_at_least()`` to round up timeouts in a more
283*61c4878aSAndroid Build Coastguard Worker   explicit, self documenting manner which uses ``std::chrono::ceil``
284*61c4878aSAndroid Build Coastguard Worker   internally.
285*61c4878aSAndroid Build Coastguard Worker
286*61c4878aSAndroid Build Coastguard WorkerUse of ``count()`` and ``time_since_epoch()``
287*61c4878aSAndroid Build Coastguard Worker=============================================
288*61c4878aSAndroid Build Coastguard WorkerIt's easy to escape the typesafe chrono types through the use of
289*61c4878aSAndroid Build Coastguard Worker``duration<>::count()`` and ``time_point<>::time_since_epoch()``, however this
290*61c4878aSAndroid Build Coastguard Workerincreases the risk of accidentally introduce conversion and arithmetic errors.
291*61c4878aSAndroid Build Coastguard Worker
292*61c4878aSAndroid Build Coastguard WorkerFor this reason, avoid these two escape hatches until it's absolutely necessary
293*61c4878aSAndroid Build Coastguard Workerdue to I/O such as RPCs or writing to non-volatile storage.
294*61c4878aSAndroid Build Coastguard Worker
295*61c4878aSAndroid Build Coastguard WorkerDiscrete Timeouts
296*61c4878aSAndroid Build Coastguard Worker=================
297*61c4878aSAndroid Build Coastguard WorkerWe briefly want to mention a common pitfall when working with discrete
298*61c4878aSAndroid Build Coastguard Workerrepresentations of time durations for timeouts (ticks and real time units)
299*61c4878aSAndroid Build Coastguard Workeron systems with a continously running clock which is backed by discrete time
300*61c4878aSAndroid Build Coastguard Workerintervals (i.e. whole integer constant tick periods).
301*61c4878aSAndroid Build Coastguard Worker
302*61c4878aSAndroid Build Coastguard WorkerImagine an RTOS system where we have a constant tick interval. If we attempt to
303*61c4878aSAndroid Build Coastguard Workersleep for 1 tick, how long will the kernel actually let us sleep?
304*61c4878aSAndroid Build Coastguard Worker
305*61c4878aSAndroid Build Coastguard WorkerIn most kernels you will end up sleeping somewhere between 0 and 1 tick periods
306*61c4878aSAndroid Build Coastguard Workerinclusively, i.e. ``[0, 1]``, if we ignore scheduling latency and preemption.
307*61c4878aSAndroid Build Coastguard Worker**This means it can randomly be non-blocking vs blocking!**
308*61c4878aSAndroid Build Coastguard Worker
309*61c4878aSAndroid Build Coastguard WorkerThis is because internally kernels use a decrementing timeout counter or a
310*61c4878aSAndroid Build Coastguard Workerdeadline without taking the current current progression through the existing
311*61c4878aSAndroid Build Coastguard Workertick period into account.
312*61c4878aSAndroid Build Coastguard Worker
313*61c4878aSAndroid Build Coastguard WorkerFor this reason all of Pigweed's time bound APIs will internally add an extra
314*61c4878aSAndroid Build Coastguard Workertick to timeout intents when needed to guarantee that we will block for at least
315*61c4878aSAndroid Build Coastguard Workerthe specified timeout.
316*61c4878aSAndroid Build Coastguard Worker
317*61c4878aSAndroid Build Coastguard WorkerThis same risk exists if a continuously running hardware timer is used for a
318*61c4878aSAndroid Build Coastguard Workersoftware timer service.
319*61c4878aSAndroid Build Coastguard Worker
320*61c4878aSAndroid Build Coastguard Worker.. Note::
321*61c4878aSAndroid Build Coastguard Worker   When calculating deadlines based on a ``pw::chrono::SystemClock::timeout``,
322*61c4878aSAndroid Build Coastguard Worker   use ``SystemClock::TimePointAfterAtLeast()`` which adds an extra tick for you
323*61c4878aSAndroid Build Coastguard Worker   internally.
324*61c4878aSAndroid Build Coastguard Worker
325*61c4878aSAndroid Build Coastguard Worker------
326*61c4878aSAndroid Build Coastguard WorkerClocks
327*61c4878aSAndroid Build Coastguard Worker------
328*61c4878aSAndroid Build Coastguard WorkerWe do not recomend using the clocks provided by ``<chrono>`` including but not
329*61c4878aSAndroid Build Coastguard Workerlimited to the ``std::chrono::system_clock``, ``std::chrono::steady_clock``, and
330*61c4878aSAndroid Build Coastguard Worker``std::chrono::high_resolution_clock``. These clocks typically do not work on
331*61c4878aSAndroid Build Coastguard Workerembedded systems, as they are not backed by any actual clocks although they
332*61c4878aSAndroid Build Coastguard Workeroften do compile. In addition, their APIs miss guarantees and parameters which
333*61c4878aSAndroid Build Coastguard Workermake them difficult and risky to use on embedded systems.
334*61c4878aSAndroid Build Coastguard Worker
335*61c4878aSAndroid Build Coastguard WorkerIn addition, the STL time bound APIs heavily rely on templating to permit
336*61c4878aSAndroid Build Coastguard Workerdifferent clocks and durations to be used. We believe this level of template
337*61c4878aSAndroid Build Coastguard Workermetaprogramming and the indirection that comes with that can be confusing. On
338*61c4878aSAndroid Build Coastguard Workertop of this, accidental use of the wrong clock and/or conversions between them
339*61c4878aSAndroid Build Coastguard Workeris a frequent source of bugs. For example using a real time clock which is not
340*61c4878aSAndroid Build Coastguard Workermonotonic for a timeout or deadline can wreak havoc when the clock is adjusted.
341*61c4878aSAndroid Build Coastguard Worker
342*61c4878aSAndroid Build Coastguard WorkerFor this reason Pigweed's timeout and deadline APIs will not permit arbitrary
343*61c4878aSAndroid Build Coastguard Workerclock and duration selection. Outside of small templated helpers, all APIs will
344*61c4878aSAndroid Build Coastguard Workerrequire a specific clock's duration and/or time-point. For almost all of Pigweed
345*61c4878aSAndroid Build Coastguard Workerthis means that the ``pw::chrono::SystemClock`` is used which is usually backed
346*61c4878aSAndroid Build Coastguard Workerby the kernel's clock.
347*61c4878aSAndroid Build Coastguard Worker
348*61c4878aSAndroid Build Coastguard WorkerPigweedClock Requirements
349*61c4878aSAndroid Build Coastguard Worker=========================
350*61c4878aSAndroid Build Coastguard Worker``pw_chrono`` extends the C++ named
351*61c4878aSAndroid Build Coastguard Worker`Clock <https://en.cppreference.com/w/cpp/named_req/Clock>`_ and
352*61c4878aSAndroid Build Coastguard Worker`TrivialClock <https://en.cppreference.com/w/cpp/named_req/TrivialClock>`_
353*61c4878aSAndroid Build Coastguard Workerrequirements with the ``PigweedClock Requirements`` to make clocks more friendly
354*61c4878aSAndroid Build Coastguard Workerfor embedded systems.
355*61c4878aSAndroid Build Coastguard Worker
356*61c4878aSAndroid Build Coastguard WorkerThis permits the clock compatibility to be verified through ``static_assert`` at
357*61c4878aSAndroid Build Coastguard Workercompile time which the STL's requirements do not address. For example whether
358*61c4878aSAndroid Build Coastguard Workerthe clock continues to tick while interrupts are masked or whether the clock is
359*61c4878aSAndroid Build Coastguard Workermonotonic even if the clock period may not be steady due to the use of low power
360*61c4878aSAndroid Build Coastguard Workersleep modes.
361*61c4878aSAndroid Build Coastguard Worker
362*61c4878aSAndroid Build Coastguard WorkerFor a type ``PWC`` to meet the ``PigweedClock Requirements``:
363*61c4878aSAndroid Build Coastguard Worker
364*61c4878aSAndroid Build Coastguard Worker* The type PWC must meet C++14's
365*61c4878aSAndroid Build Coastguard Worker  `Clock <https://en.cppreference.com/w/cpp/named_req/Clock>`_ and
366*61c4878aSAndroid Build Coastguard Worker  `TrivialClock <https://en.cppreference.com/w/cpp/named_req/TrivialClock>`_
367*61c4878aSAndroid Build Coastguard Worker  requirements.
368*61c4878aSAndroid Build Coastguard Worker* The ``PWC::rep`` must be ``int64_t`` to ensure that there cannot be any
369*61c4878aSAndroid Build Coastguard Worker  overflow risk regardless of the ``PWC::period`` configuration.
370*61c4878aSAndroid Build Coastguard Worker  This is done because we do not expect any clocks with periods coarser than
371*61c4878aSAndroid Build Coastguard Worker  seconds which already require 35 bits.
372*61c4878aSAndroid Build Coastguard Worker* ``const bool PWC::is_monotonic`` must return true if and only if the clock
373*61c4878aSAndroid Build Coastguard Worker  can never move backwards.
374*61c4878aSAndroid Build Coastguard Worker  This effectively allows one to describe an unsteady but monotonic clock by
375*61c4878aSAndroid Build Coastguard Worker  combining the C++14's Clock requirement's ``const bool PWC::is_steady``.
376*61c4878aSAndroid Build Coastguard Worker* ``const bool PWC::is_free_running`` must return true if and only if the clock
377*61c4878aSAndroid Build Coastguard Worker  continues to move forward, without risk of overflow, regardless of whether
378*61c4878aSAndroid Build Coastguard Worker  global interrupts are disabled or whether one is in a critical section or even
379*61c4878aSAndroid Build Coastguard Worker  non maskable interrupt.
380*61c4878aSAndroid Build Coastguard Worker* ``const bool PWC::is_always_enabled`` must return true if the clock is always
381*61c4878aSAndroid Build Coastguard Worker  enabled and available. If false, the clock must:
382*61c4878aSAndroid Build Coastguard Worker
383*61c4878aSAndroid Build Coastguard Worker  + Ensure the ``const bool is_{steady,monotonic,free_running}`` attributes
384*61c4878aSAndroid Build Coastguard Worker    are all valid while the clock is not enabled to ensure they properly meet
385*61c4878aSAndroid Build Coastguard Worker    the previously stated requirements.
386*61c4878aSAndroid Build Coastguard Worker  + Meet C++14's
387*61c4878aSAndroid Build Coastguard Worker    `BasicLockable <https://en.cppreference.com/w/cpp/named_req/BasicLockable>`_
388*61c4878aSAndroid Build Coastguard Worker    requirements (i.e. provide ``void lock()`` & ``void unlock()``) in order
389*61c4878aSAndroid Build Coastguard Worker    to provide ``std::scoped_lock`` support to enable a user to enable the
390*61c4878aSAndroid Build Coastguard Worker    clock.
391*61c4878aSAndroid Build Coastguard Worker  + Provide ``const bool is_{steady,monotonic,free_running}_while_enabled``
392*61c4878aSAndroid Build Coastguard Worker    attributes which meet the attributes only while the clock is enabled.
393*61c4878aSAndroid Build Coastguard Worker* ``const bool PWC::is_stopped_in_halting_debug_mode`` must return true if and
394*61c4878aSAndroid Build Coastguard Worker  only if the clock halts, without further modification, during halting debug
395*61c4878aSAndroid Build Coastguard Worker  mode , for example during a breakpoint while a hardware debugger is used.
396*61c4878aSAndroid Build Coastguard Worker* ``const Epoch PWC::epoch`` must return the epoch type of the clock, the
397*61c4878aSAndroid Build Coastguard Worker  ``Epoch`` enumeration is defined in ``pw_chrono/epoch.h``.
398*61c4878aSAndroid Build Coastguard Worker* The function ``time_point PWC::now() noexcept`` must always be thread and
399*61c4878aSAndroid Build Coastguard Worker  interrupt safe, but not necessarily non-masking and bare-metal interrupt safe.
400*61c4878aSAndroid Build Coastguard Worker* ``const bool PWC::is_non_masking_interrupt_safe`` must return true if and only
401*61c4878aSAndroid Build Coastguard Worker  if the clock is safe to use from non-masking and bare-metal interrupts.
402*61c4878aSAndroid Build Coastguard Worker
403*61c4878aSAndroid Build Coastguard WorkerThe PigweedClock requirement will not require ``now()`` to be a static function,
404*61c4878aSAndroid Build Coastguard Workerhowever the upstream façades will follow this approach.
405*61c4878aSAndroid Build Coastguard Worker
406*61c4878aSAndroid Build Coastguard WorkerSystemClock facade
407*61c4878aSAndroid Build Coastguard Worker==================
408*61c4878aSAndroid Build Coastguard WorkerThe ``pw::chrono::SystemClock`` is meant to serve as the clock used for time
409*61c4878aSAndroid Build Coastguard Workerbound operations such as thread sleeping, waiting on mutexes/semaphores, etc.
410*61c4878aSAndroid Build Coastguard WorkerThe ``SystemClock`` always uses a signed 64 bit as the underlying type for time
411*61c4878aSAndroid Build Coastguard Workerpoints and durations. This means users do not have to worry about clock overflow
412*61c4878aSAndroid Build Coastguard Workerrisk as long as rational durations and time points as used, i.e. within a range
413*61c4878aSAndroid Build Coastguard Workerof ±292 years.
414*61c4878aSAndroid Build Coastguard Worker
415*61c4878aSAndroid Build Coastguard WorkerThe ``SystemClock`` represents an unsteady, monotonic clock.
416*61c4878aSAndroid Build Coastguard Worker
417*61c4878aSAndroid Build Coastguard WorkerThe epoch of this clock is unspecified and may not be related to wall time
418*61c4878aSAndroid Build Coastguard Worker(for example, it can be time since boot). The time between ticks of this
419*61c4878aSAndroid Build Coastguard Workerclock may vary due to sleep modes and potential interrupt handling.
420*61c4878aSAndroid Build Coastguard Worker``SystemClock`` meets the requirements of C++'s ``TrivialClock`` and Pigweed's
421*61c4878aSAndroid Build Coastguard Worker``PigweedClock``.
422*61c4878aSAndroid Build Coastguard Worker
423*61c4878aSAndroid Build Coastguard WorkerThis clock is used for expressing timeout and deadline semantics with the
424*61c4878aSAndroid Build Coastguard Workerscheduler in Pigweed including pw_sync, pw_thread, etc.
425*61c4878aSAndroid Build Coastguard Worker
426*61c4878aSAndroid Build Coastguard WorkerC++
427*61c4878aSAndroid Build Coastguard Worker---
428*61c4878aSAndroid Build Coastguard Worker.. doxygenstruct:: pw::chrono::SystemClock
429*61c4878aSAndroid Build Coastguard Worker   :members:
430*61c4878aSAndroid Build Coastguard Worker
431*61c4878aSAndroid Build Coastguard WorkerExample in C++
432*61c4878aSAndroid Build Coastguard Worker--------------
433*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp
434*61c4878aSAndroid Build Coastguard Worker
435*61c4878aSAndroid Build Coastguard Worker   #include <chrono>
436*61c4878aSAndroid Build Coastguard Worker
437*61c4878aSAndroid Build Coastguard Worker   #include "pw_chrono/system_clock.h"
438*61c4878aSAndroid Build Coastguard Worker
439*61c4878aSAndroid Build Coastguard Worker   void Foo() {
440*61c4878aSAndroid Build Coastguard Worker     const SystemClock::time_point before = SystemClock::now();
441*61c4878aSAndroid Build Coastguard Worker     TakesALongTime();
442*61c4878aSAndroid Build Coastguard Worker     const SystemClock::duration time_taken = SystemClock::now() - before;
443*61c4878aSAndroid Build Coastguard Worker     bool took_way_too_long = false;
444*61c4878aSAndroid Build Coastguard Worker     if (time_taken > std::chrono::seconds(42)) {
445*61c4878aSAndroid Build Coastguard Worker       took_way_too_long = true;
446*61c4878aSAndroid Build Coastguard Worker     }
447*61c4878aSAndroid Build Coastguard Worker   }
448*61c4878aSAndroid Build Coastguard Worker
449*61c4878aSAndroid Build Coastguard WorkerVirtualClock
450*61c4878aSAndroid Build Coastguard Worker============
451*61c4878aSAndroid Build Coastguard WorkerPigweed also includes a virtual base class for timers,
452*61c4878aSAndroid Build Coastguard Worker:cpp:class:`pw::chrono::VirtualClock`. This class allows for writing
453*61c4878aSAndroid Build Coastguard Workertiming-sensitive code that can be tested using simulated clocks such as
454*61c4878aSAndroid Build Coastguard Worker:cpp:class:`pw::chrono::SimulatedSystemClock`.
455*61c4878aSAndroid Build Coastguard Worker
456*61c4878aSAndroid Build Coastguard WorkerUsing simulated clocks in tests allow tests to avoid sleeping or timeouts,
457*61c4878aSAndroid Build Coastguard Workerresulting in faster and more reliable tests.
458*61c4878aSAndroid Build Coastguard Worker
459*61c4878aSAndroid Build Coastguard WorkerSee also :cpp:class:`pw::async2::TimeProvider` for creating testable
460*61c4878aSAndroid Build Coastguard Workertime-sensitive code using asynchronous timers.
461*61c4878aSAndroid Build Coastguard Worker
462*61c4878aSAndroid Build Coastguard Worker.. doxygenclass:: pw::chrono::VirtualClock
463*61c4878aSAndroid Build Coastguard Worker  :members:
464*61c4878aSAndroid Build Coastguard Worker
465*61c4878aSAndroid Build Coastguard Worker.. doxygenclass:: pw::chrono::SimulatedSystemClock
466*61c4878aSAndroid Build Coastguard Worker  :members:
467*61c4878aSAndroid Build Coastguard Worker
468*61c4878aSAndroid Build Coastguard Worker
469*61c4878aSAndroid Build Coastguard Worker
470*61c4878aSAndroid Build Coastguard WorkerProtobuf
471*61c4878aSAndroid Build Coastguard Worker========
472*61c4878aSAndroid Build Coastguard WorkerSometimes it's desirable to communicate high resolution time points and
473*61c4878aSAndroid Build Coastguard Workerdurations from one device to another. For this, ``pw_chrono`` provides protobuf
474*61c4878aSAndroid Build Coastguard Workerrepresentations of clock parameters (``pw.chrono.ClockParameters``) and time
475*61c4878aSAndroid Build Coastguard Workerpoints (``pw.chrono.TimePoint``). These types are less succinct than simple
476*61c4878aSAndroid Build Coastguard Workersingle-purpose fields like ``ms_since_boot`` or ``unix_timestamp``, but allow
477*61c4878aSAndroid Build Coastguard Workertimestamps to be communicated in terms of the tick rate of a device, potentially
478*61c4878aSAndroid Build Coastguard Workerproviding significantly higher resolution. Logging, tracing, and system state
479*61c4878aSAndroid Build Coastguard Workersnapshots are use cases that benefit from this additional resolution.
480*61c4878aSAndroid Build Coastguard Worker
481*61c4878aSAndroid Build Coastguard WorkerThis module provides an overlay proto (``pw.chrono.SnapshotTimestamps``) for
482*61c4878aSAndroid Build Coastguard Workerusage with ``pw_snapshot`` to encourage capture of high resolution timestamps
483*61c4878aSAndroid Build Coastguard Workerin device snapshots. Simplified capture utilies and host-side tooling to
484*61c4878aSAndroid Build Coastguard Workerinterpret this data are not yet provided by ``pw_chrono``.
485*61c4878aSAndroid Build Coastguard Worker
486*61c4878aSAndroid Build Coastguard WorkerThere is tooling that take these proto and make them more human readable.
487*61c4878aSAndroid Build Coastguard Worker
488*61c4878aSAndroid Build Coastguard Worker---------------
489*61c4878aSAndroid Build Coastguard WorkerSoftware Timers
490*61c4878aSAndroid Build Coastguard Worker---------------
491*61c4878aSAndroid Build Coastguard Worker
492*61c4878aSAndroid Build Coastguard WorkerSystemTimer facade
493*61c4878aSAndroid Build Coastguard Worker==================
494*61c4878aSAndroid Build Coastguard WorkerThe SystemTimer facade enables deferring execution of a callback until a later
495*61c4878aSAndroid Build Coastguard Workertime. For example, enabling low power mode after a period of inactivity.
496*61c4878aSAndroid Build Coastguard Worker
497*61c4878aSAndroid Build Coastguard WorkerThe base SystemTimer only supports a one-shot style timer with a callback.
498*61c4878aSAndroid Build Coastguard WorkerA periodic timer can be implemented by rescheduling the timer in the callback
499*61c4878aSAndroid Build Coastguard Workerthrough ``InvokeAt(kDesiredPeriod + expired_deadline)``.
500*61c4878aSAndroid Build Coastguard Worker
501*61c4878aSAndroid Build Coastguard WorkerWhen implementing a periodic layer on top, the user should be mindful of
502*61c4878aSAndroid Build Coastguard Workerhandling missed periodic callbacks. They could opt to invoke the callback
503*61c4878aSAndroid Build Coastguard Workermultiple times with the expected ``expired_deadline`` values or instead saturate
504*61c4878aSAndroid Build Coastguard Workerand invoke the callback only once with the latest ``expired_deadline``.
505*61c4878aSAndroid Build Coastguard Worker
506*61c4878aSAndroid Build Coastguard WorkerThe entire API is thread safe, however it is NOT always IRQ safe.
507*61c4878aSAndroid Build Coastguard Worker
508*61c4878aSAndroid Build Coastguard WorkerThe ExpiryCallback is either invoked from a high priority thread or an
509*61c4878aSAndroid Build Coastguard Workerinterrupt. Ergo ExpiryCallbacks should be treated as if they are executed by an
510*61c4878aSAndroid Build Coastguard Workerinterrupt, meaning:
511*61c4878aSAndroid Build Coastguard Worker
512*61c4878aSAndroid Build Coastguard Worker* Processing inside of the callback should be kept to a minimum.
513*61c4878aSAndroid Build Coastguard Worker
514*61c4878aSAndroid Build Coastguard Worker* Callbacks should never attempt to block.
515*61c4878aSAndroid Build Coastguard Worker
516*61c4878aSAndroid Build Coastguard Worker* APIs which are not interrupt safe such as pw::sync::Mutex should not be used!
517*61c4878aSAndroid Build Coastguard Worker
518*61c4878aSAndroid Build Coastguard WorkerC++
519*61c4878aSAndroid Build Coastguard Worker---
520*61c4878aSAndroid Build Coastguard Worker.. doxygenclass:: pw::chrono::SystemTimer
521*61c4878aSAndroid Build Coastguard Worker   :members:
522*61c4878aSAndroid Build Coastguard Worker
523*61c4878aSAndroid Build Coastguard Worker.. cpp:namespace-push:: pw::chrono::SystemTimer
524*61c4878aSAndroid Build Coastguard Worker
525*61c4878aSAndroid Build Coastguard Worker.. list-table::
526*61c4878aSAndroid Build Coastguard Worker   :widths: 70 10 10 10
527*61c4878aSAndroid Build Coastguard Worker   :header-rows: 1
528*61c4878aSAndroid Build Coastguard Worker
529*61c4878aSAndroid Build Coastguard Worker   * - Safe to use in context
530*61c4878aSAndroid Build Coastguard Worker     - Thread
531*61c4878aSAndroid Build Coastguard Worker     - Interrupt
532*61c4878aSAndroid Build Coastguard Worker     - NMI
533*61c4878aSAndroid Build Coastguard Worker   * - :cpp:func:`pw::chrono::SystemTimer::SystemTimer`
534*61c4878aSAndroid Build Coastguard Worker     - ✔
535*61c4878aSAndroid Build Coastguard Worker     -
536*61c4878aSAndroid Build Coastguard Worker     -
537*61c4878aSAndroid Build Coastguard Worker   * - :cpp:func:`pw::chrono::SystemTimer::~SystemTimer`
538*61c4878aSAndroid Build Coastguard Worker     - ✔
539*61c4878aSAndroid Build Coastguard Worker     -
540*61c4878aSAndroid Build Coastguard Worker     -
541*61c4878aSAndroid Build Coastguard Worker   * - :cpp:func:`InvokeAfter`
542*61c4878aSAndroid Build Coastguard Worker     - ✔
543*61c4878aSAndroid Build Coastguard Worker     -
544*61c4878aSAndroid Build Coastguard Worker     -
545*61c4878aSAndroid Build Coastguard Worker   * - :cpp:func:`InvokeAt`
546*61c4878aSAndroid Build Coastguard Worker     - ✔
547*61c4878aSAndroid Build Coastguard Worker     -
548*61c4878aSAndroid Build Coastguard Worker     -
549*61c4878aSAndroid Build Coastguard Worker   * - :cpp:func:`Cancel`
550*61c4878aSAndroid Build Coastguard Worker     - ✔
551*61c4878aSAndroid Build Coastguard Worker     -
552*61c4878aSAndroid Build Coastguard Worker     -
553*61c4878aSAndroid Build Coastguard Worker
554*61c4878aSAndroid Build Coastguard Worker.. cpp:namespace-pop::
555*61c4878aSAndroid Build Coastguard Worker
556*61c4878aSAndroid Build Coastguard WorkerExample in C++
557*61c4878aSAndroid Build Coastguard Worker--------------
558*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp
559*61c4878aSAndroid Build Coastguard Worker
560*61c4878aSAndroid Build Coastguard Worker   #include "pw_chrono/system_clock.h"
561*61c4878aSAndroid Build Coastguard Worker   #include "pw_chrono/system_timer.h"
562*61c4878aSAndroid Build Coastguard Worker   #include "pw_log/log.h"
563*61c4878aSAndroid Build Coastguard Worker
564*61c4878aSAndroid Build Coastguard Worker   using namespace std::chrono_literals;
565*61c4878aSAndroid Build Coastguard Worker
566*61c4878aSAndroid Build Coastguard Worker   void DoFoo(pw::chrono::SystemClock::time_point expired_deadline) {
567*61c4878aSAndroid Build Coastguard Worker     PW_LOG_INFO("Timer callback invoked!");
568*61c4878aSAndroid Build Coastguard Worker   }
569*61c4878aSAndroid Build Coastguard Worker
570*61c4878aSAndroid Build Coastguard Worker   pw::chrono::SystemTimer foo_timer(DoFoo);
571*61c4878aSAndroid Build Coastguard Worker
572*61c4878aSAndroid Build Coastguard Worker   void DoFooLater() {
573*61c4878aSAndroid Build Coastguard Worker     foo_timer.InvokeAfter(42ms);  // DoFoo will be invoked after 42ms.
574*61c4878aSAndroid Build Coastguard Worker   }
575*61c4878aSAndroid Build Coastguard Worker
576*61c4878aSAndroid Build Coastguard Worker.. _module-pw_chrono-libc-time-wrappers:
577*61c4878aSAndroid Build Coastguard Worker
578*61c4878aSAndroid Build Coastguard Worker------------------
579*61c4878aSAndroid Build Coastguard Workerlibc time wrappers
580*61c4878aSAndroid Build Coastguard Worker------------------
581*61c4878aSAndroid Build Coastguard WorkerThe `gettimeofday <https://pubs.opengroup.org/onlinepubs/9699919799/functions/gettimeofday.html>`__
582*61c4878aSAndroid Build Coastguard Workerand `time <https://pubs.opengroup.org/onlinepubs/9699919799/functions/time.html>`__
583*61c4878aSAndroid Build Coastguard WorkerPOSIX functions are defined to return the current time since the Epoch.
584*61c4878aSAndroid Build Coastguard WorkerThe default ``pw_toolchain/arg_gcc:newlib_os_interface_stubs`` stub for
585*61c4878aSAndroid Build Coastguard Worker``gettimeofday`` will cause a linker error if any code tried to use this
586*61c4878aSAndroid Build Coastguard Workerfunction, but it's common for software not written for embedded systems to
587*61c4878aSAndroid Build Coastguard Workerdepend on this function being defined and returning something that increments
588*61c4878aSAndroid Build Coastguard Workerlike a clock. In addition, some software depends on having ``gettimeofday``
589*61c4878aSAndroid Build Coastguard Workerreturn something much closer to the actual time so it can compare against well
590*61c4878aSAndroid Build Coastguard Workerknown time points inside TLS certificates for instance.
591*61c4878aSAndroid Build Coastguard Worker
592*61c4878aSAndroid Build Coastguard WorkerFor compatibility with such software, ``pw_toolchain`` provides two different
593*61c4878aSAndroid Build Coastguard Workeroptions to wrap libc time functions. Both of these are not recommended for
594*61c4878aSAndroid Build Coastguard Workergeneral time querying and are only intended to provide compatibility.
595*61c4878aSAndroid Build Coastguard Worker
596*61c4878aSAndroid Build Coastguard Worker``pw_chrono:wrap_time_build_time``
597*61c4878aSAndroid Build Coastguard Worker==================================
598*61c4878aSAndroid Build Coastguard WorkerWrap ``gettimeofday`` and ``time`` with an implementation that returns a static
599*61c4878aSAndroid Build Coastguard Workertime value at which the library was built. Use this option if you need these
600*61c4878aSAndroid Build Coastguard Workerfunctions to return a known value greater than some point in the past.
601*61c4878aSAndroid Build Coastguard Worker
602*61c4878aSAndroid Build Coastguard Worker.. note::
603*61c4878aSAndroid Build Coastguard Worker   When building with Bazel, use the `--stamp
604*61c4878aSAndroid Build Coastguard Worker   <https://bazel.build/docs/user-manual#stamp>`__ flag when building release
605*61c4878aSAndroid Build Coastguard Worker   binaries to ensure the build time reflects the actual time the build is
606*61c4878aSAndroid Build Coastguard Worker   executed, as opposed to a cached value.
607*61c4878aSAndroid Build Coastguard Worker
608*61c4878aSAndroid Build Coastguard Worker``pw_chrono:wrap_time_system_clock``
609*61c4878aSAndroid Build Coastguard Worker====================================
610*61c4878aSAndroid Build Coastguard WorkerWrap ``gettimeofday`` and ``time`` with an implementation that uses
611*61c4878aSAndroid Build Coastguard Worker``pw::chrono::SystemClock`` to return the current time. Note the epoch is
612*61c4878aSAndroid Build Coastguard Workerdetermined by the SystemClock backend epoch, which on most embedded systems will
613*61c4878aSAndroid Build Coastguard Workerbe time since boot. Use this option if you don't care about the time returned
614*61c4878aSAndroid Build Coastguard Workerbeing close to actual time, but do care that it increments like a real clock.
615*61c4878aSAndroid Build Coastguard Worker
616*61c4878aSAndroid Build Coastguard Worker.. toctree::
617*61c4878aSAndroid Build Coastguard Worker   :hidden:
618*61c4878aSAndroid Build Coastguard Worker   :maxdepth: 1
619*61c4878aSAndroid Build Coastguard Worker
620*61c4878aSAndroid Build Coastguard Worker   Backends <backends>
621