Skip to main content

task/
metrics.rs

1//! Portable CPU activity metrics for tasks and executors (`metrics` feature).
2//!
3//! Every poll of a managed task is timed with a monotonic clock: the
4//! operating system's monotonic clock on Linux, macOS and Windows, and
5//! Embassy's clock, which each platform already provides for `sleep`,
6//! everywhere else. The clock is read twice per poll; nothing is allocated on
7//! the poll path. Per-task counters live beside the task storage slots and
8//! per-executor counters are created once per executor, so spawning allocates
9//! nothing more either.
10//!
11//! On Linux, macOS and Windows the metrics clock counts from its own first
12//! read, not from `embassy_time::Instant`'s origin: compare metrics
13//! timestamps only with each other.
14//!
15//! Without the feature, [`Manager::get_metrics`](crate::Manager::get_metrics)
16//! returns `None` and [`ExecutorActivity::measure_idle`] only runs its
17//! closure, so platforms and applications can use the API unconditionally at
18//! no cost.
19//!
20//! # What is measured
21//!
22//! Busy time is wall-clock time spent inside task polls, not processor time:
23//! on hosts, time the thread is descheduled or blocked during a poll counts
24//! as busy. Durations are rounded to the clock's resolution
25//! (`TICK_HERTZ`). With a coarse clock, such as a 32,768 Hz real-time
26//! counter, each poll is measured as a whole number of ticks; as polls start
27//! at uncorrelated phases, totals over many polls remain unbiased.
28//!
29//! Interrupt handlers that run during a task poll count as that task's busy
30//! time; those that run while the executor waits count as idle time.
31//!
32//! # Computing loads
33//!
34//! Every reported counter and executor timestamp never decreases. Consumers
35//! sample [`Manager::get_metrics`](crate::Manager::get_metrics) periodically
36//! and divide differences between two snapshots, computed with
37//! `saturating_sub`:
38//!
39//! - Match executors between snapshots by [`ExecutorMetrics::executor`], not
40//!   by [`ExecutorMetrics::spawner`]: an executor is reported under its lowest
41//!   spawner registration, which can change.
42//! - An executor's load over the window is `Δbusy / Δtimestamp` with that
43//!   executor's own [`ExecutorMetrics::timestamp_nanoseconds`]. When
44//!   [`ExecutorMetrics::idle_nanoseconds`] is available on both sides, prefer
45//!   `1 − Δidle / Δtimestamp`: it also counts executor bookkeeping and
46//!   foreign work on that core as load. Both include the poll or wait in
47//!   progress, so they are continuous. They are close to, but not strictly
48//!   within, `[0, 1]`: clamp them (see [Precision](#precision)).
49//! - A task's share is `Δbusy / Δ`[`MetricsSnapshot::timestamp_nanoseconds`].
50//!   Task busy time is added when a poll ends, so a long poll counts entirely
51//!   in the window where it ends, and the shares of one executor's tasks can
52//!   then sum above 1. Normalise per executor, grouping tasks by
53//!   [`TaskMetrics::executor`]: when their sum exceeds 1, divide each of them
54//!   by that sum rather than clamping each task separately. Compare
55//!   [`TaskMetrics::generation`] to detect a reused task identifier.
56//! - Tasks adopted rather than spawned by the manager have no counters, report
57//!   zero polls, have `spawner == usize::MAX` and no executor.
58//!
59//! # Precision
60//!
61//! Counters are kept in clock ticks and each one is converted to nanoseconds
62//! separately, rounding down. When `TICK_HERTZ` does not divide one billion,
63//! as with a 32,768 Hz counter, the difference of two converted values can
64//! exceed the converted difference by 1 ns, so `Δidle` can exceed
65//! `Δtimestamp` by 1 ns over the same ticks. On multi-core targets, a reader
66//! can also extrapolate a period in progress slightly past the value its
67//! writer finally stores (see [Concurrency](#concurrency)); the excess is
68//! kept rather than reported as a decrease. Use `saturating_sub` for every
69//! difference and clamp ratios to `[0, 1]`.
70//!
71//! # Platform hook
72//!
73//! Executor busy time is derived from task polls and needs no platform code.
74//! Idle time, the time an executor waits for work, can only be measured by the
75//! executor loop. Platforms create an [`ExecutorActivity`] on the executor's
76//! thread before its loop, and wrap their wait with
77//! [`ExecutorActivity::measure_idle`], between polls of their executor:
78//!
79//! ```ignore
80//! let activity = task::metrics::ExecutorActivity::new(executor.spawner());
81//! loop {
82//!     unsafe { executor.poll() };
83//!     activity.measure_idle(|| cortex_m::asm::wfe());
84//! }
85//! ```
86//!
87//! Once an executor's hook exists, its [`ExecutorMetrics::idle_nanoseconds`]
88//! is `Some`, starting at 0; without the hook, it is `None`. The hook is
89//! `!Send`, like the [`Spawner`](embassy_executor::Spawner) it is created
90//! from:
91//!
92//! ```compile_fail,E0277
93//! fn assert_send<T: Send>() {}
94//! assert_send::<task::metrics::ExecutorActivity>();
95//! ```
96//!
97//! # Concurrency
98//!
99//! Each executor's counters have a single writer, the executor's own thread:
100//! task polls and [`ExecutorActivity::measure_idle`], whose handle cannot
101//! leave its thread. Readers use a sequence lock built from 32-bit atomic
102//! loads and stores, so it works without compare-and-swap or 64-bit atomics,
103//! and they spin while a write is in progress, outside any critical section.
104//! Never read the counters from code that preempts a writer on the same core:
105//! an interrupt handler, or a task of an interrupt executor that preempts an
106//! instrumented thread executor. Such a reader would spin forever.
107//!
108//! Writers read the clock inside their write section, which keeps a reader
109//! from extrapolating a finished period on a single core and on x86. On
110//! weakly ordered multi-core architectures, such as AArch64 and RISC-V,
111//! fences do not order a system-register clock read after an earlier store,
112//! so a reader on another core can still extrapolate a period in progress by
113//! up to the writer's store latency. Reported values never decrease because
114//! every reader clamps its sample to a per-executor high-water mark of busy
115//! time, idle time and timestamp, updated with plain loads and stores inside a
116//! short critical section.
117
118use crate::{SpawnerIdentifier, TaskIdentifier};
119use alloc::{string::String, vec::Vec};
120
121/// Cumulative counters of one registered task.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct TaskMetrics {
124    pub identifier: TaskIdentifier,
125    /// Distinguishes registrations that reuse the same identifier.
126    pub generation: u64,
127    pub name: String,
128    /// Spawner registration running the task; `usize::MAX` for adopted tasks.
129    pub spawner: SpawnerIdentifier,
130    /// Executor running the task, as in [`ExecutorMetrics::executor`];
131    /// `None` for adopted tasks.
132    pub executor: Option<usize>,
133    pub polls: u64,
134    /// Wall-clock time spent in completed polls.
135    pub busy_nanoseconds: u64,
136    pub longest_poll_nanoseconds: u64,
137}
138
139/// Cumulative counters of one executor (a core or an operating system thread).
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub struct ExecutorMetrics {
142    /// Lowest spawner registration of this executor. It can change between
143    /// snapshots; match executors by [`Self::executor`].
144    pub spawner: SpawnerIdentifier,
145    /// Embassy executor identifier (`Spawner::executor_id`), stable for the
146    /// executor's lifetime.
147    pub executor: usize,
148    pub polls: u64,
149    /// Wall-clock time spent polling managed tasks, including a poll in
150    /// progress. Never decreases.
151    pub busy_nanoseconds: u64,
152    /// Time spent waiting for work, including a wait in progress, once the
153    /// platform executor created its [`ExecutorActivity`]. Never decreases.
154    pub idle_nanoseconds: Option<u64>,
155    /// Clock value when the counters were created.
156    pub started_nanoseconds: u64,
157    /// Clock value at which these counters were read. Divide busy and idle
158    /// differences by differences of this value. Never decreases.
159    pub timestamp_nanoseconds: u64,
160}
161
162/// Sample of all task and executor counters. Each task's and each executor's
163/// counters are read consistently; the set is not one atomic instant.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct MetricsSnapshot {
166    /// Monotonic clock value read after every counter of the snapshot, on the
167    /// same clock as the counters. Use it for task shares; executors carry
168    /// their own [`ExecutorMetrics::timestamp_nanoseconds`].
169    pub timestamp_nanoseconds: u64,
170    pub tasks: Vec<TaskMetrics>,
171    pub executors: Vec<ExecutorMetrics>,
172}
173
174/// True when the `metrics` feature instruments task polls.
175pub const ENABLED: bool = cfg!(feature = "metrics");
176
177#[cfg(feature = "metrics")]
178pub use enabled::*;
179
180#[cfg(not(feature = "metrics"))]
181pub use disabled::*;
182
183#[cfg(not(feature = "metrics"))]
184mod disabled {
185    use core::marker::PhantomData;
186    use embassy_executor::Spawner;
187
188    /// Executor idle hook; does nothing without the `metrics` feature.
189    pub struct ExecutorActivity {
190        not_send: PhantomData<*mut ()>,
191    }
192
193    impl ExecutorActivity {
194        #[inline(always)]
195        pub fn new(_spawner: Spawner) -> Self {
196            Self {
197                not_send: PhantomData,
198            }
199        }
200
201        #[inline(always)]
202        pub fn measure_idle<R>(&self, wait: impl FnOnce() -> R) -> R {
203            wait()
204        }
205    }
206}
207
208#[cfg(feature = "metrics")]
209mod enabled {
210    use super::ExecutorMetrics;
211    use alloc::{boxed::Box, vec::Vec};
212    use core::{
213        cell::{Cell, RefCell},
214        marker::PhantomData,
215    };
216    use embassy_executor::Spawner;
217    use portable_atomic::{AtomicU32, Ordering, fence};
218    use synchronization::blocking_mutex::{Mutex, raw::CriticalSectionRawMutex};
219
220    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
221    mod clock {
222        extern crate std;
223        use std::{sync::OnceLock, time::Instant};
224
225        /// The operating system's monotonic clock, in nanoseconds.
226        pub const HERTZ: u64 = 1_000_000_000;
227
228        /// Nanoseconds since the first read, an origin unrelated to
229        /// `embassy_time::Instant`'s. Embassy's std clock takes its driver's
230        /// global mutex on every read; this one is lock-free.
231        #[inline(always)]
232        pub fn now() -> u64 {
233            static ORIGIN: OnceLock<Instant> = OnceLock::new();
234            let elapsed = ORIGIN.get_or_init(Instant::now).elapsed().as_nanos();
235            u64::try_from(elapsed).unwrap_or(u64::MAX)
236        }
237    }
238
239    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
240    mod clock {
241        /// Embassy's tick rate, set by the platform's time driver.
242        pub const HERTZ: u64 = embassy_time::TICK_HZ;
243
244        #[inline(always)]
245        pub fn now() -> u64 {
246            embassy_time::Instant::now().as_ticks()
247        }
248    }
249
250    /// Resolution of the metrics clock, in ticks per second.
251    pub const TICK_HERTZ: u64 = clock::HERTZ;
252
253    /// Current clock value in ticks.
254    #[inline(always)]
255    pub(crate) fn now() -> u64 {
256        clock::now()
257    }
258
259    /// Convert clock ticks to nanoseconds, rounding down and saturating.
260    ///
261    /// When [`TICK_HERTZ`] does not divide one billion, the difference of two
262    /// converted values can exceed the converted difference by 1 ns.
263    pub fn ticks_to_nanoseconds(ticks: u64) -> u64 {
264        convert(ticks, TICK_HERTZ)
265    }
266
267    #[inline(always)]
268    fn convert(ticks: u64, hertz: u64) -> u64 {
269        if 1_000_000_000 % hertz == 0 {
270            ticks.saturating_mul(1_000_000_000 / hertz)
271        } else {
272            let nanoseconds = u128::from(ticks) * 1_000_000_000 / u128::from(hertz);
273            u64::try_from(nanoseconds).unwrap_or(u64::MAX)
274        }
275    }
276
277    /// `N` words updated together by one writer and read consistently by any
278    /// thread. Only atomic loads and stores are used, so this also works on
279    /// targets without compare-and-swap or 64-bit atomics.
280    pub(crate) struct Words<const N: usize> {
281        sequence: AtomicU32,
282        words: [AtomicU32; N],
283    }
284
285    impl<const N: usize> Words<N> {
286        pub(crate) const fn new() -> Self {
287            Self {
288                sequence: AtomicU32::new(0),
289                words: [const { AtomicU32::new(0) }; N],
290            }
291        }
292
293        /// Run `update`, which loads and stores words with [`Self::get`] and
294        /// [`Self::set`], as one atomic change for readers. Only one thread
295        /// may write at a time; ownership changes need a happens-before edge,
296        /// such as Embassy's task claim.
297        #[inline(always)]
298        pub(crate) fn write(&self, update: impl FnOnce(&Self)) {
299            let sequence = self.sequence.load(Ordering::Relaxed);
300            self.sequence
301                .store(sequence.wrapping_add(1), Ordering::Relaxed);
302            fence(Ordering::Release);
303            update(self);
304            self.sequence
305                .store(sequence.wrapping_add(2), Ordering::Release);
306        }
307
308        /// Like [`Self::write`], but read `clock` inside the write section,
309        /// pass it to `update` and return it.
310        ///
311        /// On a single core and on x86, the clock is read only once the odd
312        /// sequence is visible, so a reader whose own clock read is later
313        /// sees the write and retries instead of extrapolating a period in
314        /// progress past the value this write stores. Weakly ordered
315        /// architectures do not order a system-register clock read after the
316        /// fence; readers clamp their samples for those.
317        #[inline(always)]
318        pub(crate) fn write_at(
319            &self,
320            clock: impl FnOnce() -> u64,
321            update: impl FnOnce(&Self, u64),
322        ) -> u64 {
323            let sequence = self.sequence.load(Ordering::Relaxed);
324            self.sequence
325                .store(sequence.wrapping_add(1), Ordering::Relaxed);
326            // Store-to-load ordering needs a full fence.
327            fence(Ordering::SeqCst);
328            let at = clock();
329            update(self, at);
330            self.sequence
331                .store(sequence.wrapping_add(2), Ordering::Release);
332            at
333        }
334
335        /// Writer-side load; readers use [`Self::read`].
336        #[inline(always)]
337        pub(crate) fn get(&self, index: usize) -> u32 {
338            self.words[index].load(Ordering::Relaxed)
339        }
340
341        #[inline(always)]
342        pub(crate) fn set(&self, index: usize, value: u32) {
343            self.words[index].store(value, Ordering::Relaxed);
344        }
345
346        #[inline(always)]
347        fn get64(&self, index: usize) -> u64 {
348            u64::from(self.get(index)) | (u64::from(self.get(index + 1)) << 32)
349        }
350
351        #[inline(always)]
352        fn set64(&self, index: usize, value: u64) {
353            self.set(index, value as u32);
354            self.set(index + 1, (value >> 32) as u32);
355        }
356
357        #[inline(always)]
358        fn add64(&self, index: usize, value: u64) {
359            self.set64(index, self.get64(index).wrapping_add(value));
360        }
361
362        pub(crate) fn read(&self) -> [u32; N] {
363            self.read_at(|| ()).0
364        }
365
366        /// Read all words consistently, and `clock` after loading them and
367        /// before confirming that no write started meanwhile. Pairs with
368        /// [`Self::write_at`].
369        pub(crate) fn read_at<T>(&self, mut clock: impl FnMut() -> T) -> ([u32; N], T) {
370            loop {
371                let before = self.sequence.load(Ordering::Acquire);
372                if before & 1 == 0 {
373                    let values =
374                        core::array::from_fn(|index| self.words[index].load(Ordering::Relaxed));
375                    fence(Ordering::SeqCst);
376                    let at = clock();
377                    fence(Ordering::SeqCst);
378                    if self.sequence.load(Ordering::Relaxed) == before {
379                        return (values, at);
380                    }
381                }
382                core::hint::spin_loop();
383            }
384        }
385    }
386
387    fn get64(words: &[u32], index: usize) -> u64 {
388        u64::from(words[index]) | (u64::from(words[index + 1]) << 32)
389    }
390
391    const TASK_BUSY: usize = 0;
392    const TASK_POLLS: usize = 2;
393    const TASK_LONGEST: usize = 4;
394    const TASK_WORDS: usize = 6;
395
396    /// Per-slot task counters, in ticks. Retained with their storage slot and
397    /// reset when the slot is claimed by a new task.
398    pub(crate) struct TaskCounters(Words<TASK_WORDS>);
399
400    /// Task counters in ticks.
401    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
402    pub(crate) struct TaskSample {
403        pub(crate) polls: u64,
404        pub(crate) busy: u64,
405        pub(crate) longest_poll: u64,
406    }
407
408    impl TaskCounters {
409        pub(crate) const fn new() -> Self {
410            Self(Words::new())
411        }
412
413        pub(crate) fn reset(&self) {
414            self.0
415                .write(|words| (0..TASK_WORDS).for_each(|index| words.set(index, 0)));
416        }
417
418        #[inline(always)]
419        pub(crate) fn record_poll(&self, elapsed: u64) {
420            self.0.write(|words| {
421                words.add64(TASK_BUSY, elapsed);
422                words.add64(TASK_POLLS, 1);
423                if elapsed > words.get64(TASK_LONGEST) {
424                    words.set64(TASK_LONGEST, elapsed);
425                }
426            });
427        }
428
429        pub(crate) fn sample(&self) -> TaskSample {
430            let words = self.0.read();
431            TaskSample {
432                polls: get64(&words, TASK_POLLS),
433                busy: get64(&words, TASK_BUSY),
434                longest_poll: get64(&words, TASK_LONGEST),
435            }
436        }
437    }
438
439    /// Counters of one spawned task and of the executor polling it.
440    #[derive(Clone, Copy)]
441    pub(crate) struct TaskInstrumentation {
442        pub(crate) task: &'static TaskCounters,
443        pub(crate) executor: &'static ExecutorCounters,
444    }
445
446    const EXECUTOR_BUSY: usize = 0;
447    const EXECUTOR_IDLE: usize = 2;
448    const EXECUTOR_POLLS: usize = 4;
449    const EXECUTOR_SINCE: usize = 6;
450    const EXECUTOR_STATE: usize = 8;
451
452    /// Executor state in the low bits; zero between polls and waits.
453    const STATE_MASK: u32 = 0b11;
454    const STATE_BUSY: u32 = 1;
455    const STATE_IDLE: u32 = 2;
456    /// Set once the platform created the executor's idle hook.
457    const IDLE_MEASURED: u32 = 0b100;
458
459    /// Highest busy time, idle time and timestamp, in ticks, reported so far.
460    #[derive(Clone, Copy, Default)]
461    struct HighWater {
462        busy: u64,
463        idle: u64,
464        at: u64,
465    }
466
467    /// Busy and idle counters of one executor, shared by its spawner
468    /// registrations and written only by the executor's thread.
469    pub(crate) struct ExecutorCounters {
470        executor: usize,
471        started: u64,
472        words: Words<9>,
473        /// Shared by readers and updated only inside its critical section,
474        /// so no compare-and-swap is needed.
475        high_water: Mutex<CriticalSectionRawMutex, Cell<HighWater>>,
476    }
477
478    static EXECUTORS: Mutex<CriticalSectionRawMutex, RefCell<Vec<&'static ExecutorCounters>>> =
479        Mutex::new(RefCell::new(Vec::new()));
480
481    impl ExecutorCounters {
482        pub(crate) const fn new(executor: usize, started: u64) -> Self {
483            Self {
484                executor,
485                started,
486                words: Words::new(),
487                high_water: Mutex::new(Cell::new(HighWater {
488                    busy: 0,
489                    idle: 0,
490                    at: started,
491                })),
492            }
493        }
494
495        /// Counters of the executor `executor` (`Spawner::executor_id`),
496        /// created on first use and kept for the program's lifetime.
497        pub(crate) fn get(executor: usize) -> &'static Self {
498            EXECUTORS.lock(|executors| {
499                let mut executors = executors.borrow_mut();
500                if let Some(counters) = executors
501                    .iter()
502                    .find(|counters| counters.executor == executor)
503                {
504                    return *counters;
505                }
506                let counters: &'static Self = Box::leak(Box::new(Self::new(executor, now())));
507                executors.push(counters);
508                counters
509            })
510        }
511
512        pub(crate) fn executor(&self) -> usize {
513            self.executor
514        }
515
516        /// Start a task poll; returns its start time in ticks.
517        #[inline(always)]
518        pub(crate) fn begin_poll(&self) -> u64 {
519            self.begin(STATE_BUSY, now)
520        }
521
522        /// End the poll or wait in progress; returns its end time in ticks.
523        #[inline(always)]
524        pub(crate) fn end_period(&self) -> u64 {
525            self.end(now)
526        }
527
528        /// Report idle time from now on, starting at zero.
529        fn measure_idle(&self) {
530            self.words.write(|words| {
531                words.set(EXECUTOR_STATE, words.get(EXECUTOR_STATE) | IDLE_MEASURED);
532            });
533        }
534
535        #[inline(always)]
536        fn begin(&self, state: u32, clock: impl FnOnce() -> u64) -> u64 {
537            self.words.write_at(clock, |words, at| {
538                words.set64(EXECUTOR_SINCE, at);
539                let mut flags = words.get(EXECUTOR_STATE) & IDLE_MEASURED;
540                if state == STATE_IDLE {
541                    flags |= IDLE_MEASURED;
542                }
543                words.set(EXECUTOR_STATE, state | flags);
544            })
545        }
546
547        #[inline(always)]
548        fn end(&self, clock: impl FnOnce() -> u64) -> u64 {
549            self.words.write_at(clock, |words, at| {
550                let elapsed = at.saturating_sub(words.get64(EXECUTOR_SINCE));
551                let state = words.get(EXECUTOR_STATE);
552                match state & STATE_MASK {
553                    STATE_BUSY => {
554                        words.add64(EXECUTOR_BUSY, elapsed);
555                        words.add64(EXECUTOR_POLLS, 1);
556                    }
557                    STATE_IDLE => words.add64(EXECUTOR_IDLE, elapsed),
558                    _ => {}
559                }
560                words.set(EXECUTOR_STATE, state & !STATE_MASK);
561            })
562        }
563
564        /// Counters now, including the period in progress.
565        pub(crate) fn sample(&self, spawner: usize) -> ExecutorMetrics {
566            self.sample_at(spawner, now)
567        }
568
569        fn sample_at(&self, spawner: usize, clock: impl FnMut() -> u64) -> ExecutorMetrics {
570            let (words, at) = self.words.read_at(clock);
571            let mut busy = get64(&words, EXECUTOR_BUSY);
572            let mut idle = get64(&words, EXECUTOR_IDLE);
573            let current = at.saturating_sub(get64(&words, EXECUTOR_SINCE));
574            match words[EXECUTOR_STATE] & STATE_MASK {
575                STATE_BUSY => busy = busy.wrapping_add(current),
576                STATE_IDLE => idle = idle.wrapping_add(current),
577                _ => {}
578            }
579            // Never report less than an earlier reader, which may have
580            // extrapolated a period in progress past its final value.
581            let reported = self.high_water.lock(|high_water| {
582                let previous = high_water.get();
583                let reported = HighWater {
584                    busy: busy.max(previous.busy),
585                    idle: idle.max(previous.idle),
586                    at: at.max(previous.at),
587                };
588                high_water.set(reported);
589                reported
590            });
591            ExecutorMetrics {
592                spawner,
593                executor: self.executor,
594                polls: get64(&words, EXECUTOR_POLLS),
595                busy_nanoseconds: ticks_to_nanoseconds(reported.busy),
596                idle_nanoseconds: (words[EXECUTOR_STATE] & IDLE_MEASURED != 0)
597                    .then(|| ticks_to_nanoseconds(reported.idle)),
598                started_nanoseconds: ticks_to_nanoseconds(self.started),
599                timestamp_nanoseconds: ticks_to_nanoseconds(reported.at),
600            }
601        }
602    }
603
604    /// Idle-time hook of one executor, for the platform's executor loop.
605    ///
606    /// It is created from the executor's [`Spawner`] and, like it, is
607    /// `!Send`, so it stays on the executor's thread, the only writer of the
608    /// executor's counters.
609    pub struct ExecutorActivity {
610        counters: &'static ExecutorCounters,
611        not_send: PhantomData<*mut ()>,
612    }
613
614    impl ExecutorActivity {
615        /// Hook of the executor that owns `spawner`. Create it on the
616        /// executor's thread, outside a poll. From then on, the executor
617        /// reports idle time, starting at zero.
618        pub fn new(spawner: Spawner) -> Self {
619            let counters = ExecutorCounters::get(spawner.executor_id());
620            counters.measure_idle();
621            Self {
622                counters,
623                not_send: PhantomData,
624            }
625        }
626
627        /// Run the executor's wait for work, counting its duration as idle.
628        /// Call it between polls of the executor, never from a task.
629        #[inline]
630        pub fn measure_idle<R>(&self, wait: impl FnOnce() -> R) -> R {
631            debug_assert_eq!(
632                self.counters.words.get(EXECUTOR_STATE) & STATE_MASK,
633                0,
634                "measure_idle called during a poll"
635            );
636            self.counters.begin(STATE_IDLE, now);
637            let result = wait();
638            self.counters.end_period();
639            result
640        }
641    }
642
643    #[cfg(test)]
644    mod tests {
645        use super::*;
646
647        #[test]
648        fn task_counters_accumulate_with_a_test_clock() {
649            let counters = TaskCounters::new();
650            counters.record_poll(3);
651            counters.record_poll(10);
652            counters.record_poll(0);
653            assert_eq!(
654                counters.sample(),
655                TaskSample {
656                    polls: 3,
657                    busy: 13,
658                    longest_poll: 10
659                }
660            );
661            counters.reset();
662            assert_eq!(counters.sample(), TaskSample::default());
663        }
664
665        #[test]
666        fn task_counters_carry_into_the_high_word() {
667            let counters = TaskCounters::new();
668            counters.record_poll(u64::from(u32::MAX));
669            counters.record_poll(2);
670            counters.record_poll(u64::MAX / 4);
671            let sample = counters.sample();
672            assert_eq!(sample.busy, u64::from(u32::MAX) + 2 + u64::MAX / 4);
673            // The longest poll is 64 bits wide: nanosecond clocks pass
674            // 32 bits after about 4.3 seconds.
675            assert_eq!(sample.longest_poll, u64::MAX / 4);
676        }
677
678        #[test]
679        fn executor_busy_and_idle_with_a_test_clock() {
680            let counters = ExecutorCounters::new(1, 100);
681            let at = |ticks| counters.sample_at(7, || ticks);
682            assert_eq!(at(100).busy_nanoseconds, 0);
683            assert_eq!(at(100).idle_nanoseconds, None);
684
685            assert_eq!(counters.begin(STATE_BUSY, || 110), 110);
686            // A poll in progress is already visible.
687            assert_eq!(at(115).busy_nanoseconds, ticks_to_nanoseconds(5));
688            assert_eq!(counters.end(|| 120), 120);
689            counters.begin(STATE_IDLE, || 120);
690            assert_eq!(at(150).idle_nanoseconds, Some(ticks_to_nanoseconds(30)));
691            counters.end(|| 200);
692            counters.begin(STATE_BUSY, || 205);
693            counters.end(|| 206);
694
695            let sample = at(1000);
696            assert_eq!(sample.polls, 2);
697            assert_eq!(sample.spawner, 7);
698            assert_eq!(sample.executor, 1);
699            assert_eq!(sample.busy_nanoseconds, ticks_to_nanoseconds(11));
700            assert_eq!(sample.idle_nanoseconds, Some(ticks_to_nanoseconds(80)));
701            assert_eq!(sample.started_nanoseconds, ticks_to_nanoseconds(100));
702            assert_eq!(sample.timestamp_nanoseconds, ticks_to_nanoseconds(1000));
703            // Idle stays reported once measured, and counters only grow.
704            let later = at(2000);
705            assert!(later.idle_nanoseconds.is_some());
706            assert_eq!(
707                ExecutorMetrics {
708                    timestamp_nanoseconds: sample.timestamp_nanoseconds,
709                    ..later
710                },
711                sample
712            );
713        }
714
715        #[test]
716        fn creating_the_hook_reports_idle_from_zero() {
717            let counters = ExecutorCounters::new(1, 0);
718            assert_eq!(counters.sample_at(0, || 10).idle_nanoseconds, None);
719            counters.measure_idle();
720            assert_eq!(counters.sample_at(0, || 20).idle_nanoseconds, Some(0));
721            counters.begin(STATE_BUSY, || 30);
722            counters.end(|| 40);
723            // Polls keep the flag.
724            assert_eq!(counters.sample_at(0, || 50).idle_nanoseconds, Some(0));
725        }
726
727        #[test]
728        fn writers_read_the_clock_inside_the_write_section() {
729            let counters = ExecutorCounters::new(1, 0);
730            let assert_writing = || {
731                assert_eq!(counters.words.sequence.load(Ordering::Relaxed) & 1, 1);
732                10
733            };
734            counters.begin(STATE_IDLE, assert_writing);
735            counters.end(assert_writing);
736        }
737
738        #[test]
739        fn readers_retry_when_a_write_starts_before_their_clock_read() {
740            // Interleave deterministically: the writer ends an idle period
741            // between the reader's word loads and its clock read.
742            let counters = ExecutorCounters::new(1, 0);
743            counters.begin(STATE_IDLE, || 100);
744            let mut reads = 0;
745            let sample = counters.sample_at(0, || {
746                reads += 1;
747                if reads == 1 {
748                    counters.end(|| 150);
749                }
750                200
751            });
752            assert_eq!(reads, 2, "the read must retry");
753            assert_eq!(sample.idle_nanoseconds, Some(ticks_to_nanoseconds(50)));
754            // Without the retry the reader would extrapolate the finished
755            // idle period to 100 ticks.
756            assert_eq!(
757                counters.sample_at(0, || 300).idle_nanoseconds,
758                Some(ticks_to_nanoseconds(50))
759            );
760        }
761
762        /// On weakly ordered multi-core targets, a reader's clock read can
763        /// land after the writer's final clock read although the reader did
764        /// not see the write start. Simulate it with clocks out of order.
765        #[test]
766        fn readers_clamp_samples_extrapolated_past_the_final_value() {
767            let counters = ExecutorCounters::new(1, 0);
768            counters.measure_idle();
769            counters.begin(STATE_BUSY, || 100);
770            // The reader extrapolates the poll to 150 ticks.
771            let early = counters.sample_at(0, || 150);
772            assert_eq!(early.busy_nanoseconds, ticks_to_nanoseconds(50));
773            // The writer's clock read ends the poll at 140.
774            counters.end(|| 140);
775            counters.begin(STATE_IDLE, || 140);
776            // An unclamped sample would report 40 busy ticks and an earlier
777            // timestamp.
778            let late = counters.sample_at(0, || 145);
779            assert_eq!(late.busy_nanoseconds, early.busy_nanoseconds);
780            assert_eq!(late.timestamp_nanoseconds, early.timestamp_nanoseconds);
781            assert_eq!(late.idle_nanoseconds, Some(ticks_to_nanoseconds(5)));
782            // Once the real values pass the high-water mark they are
783            // reported unchanged.
784            counters.end(|| 160);
785            counters.begin(STATE_BUSY, || 160);
786            let after = counters.sample_at(0, || 175);
787            assert_eq!(after.busy_nanoseconds, ticks_to_nanoseconds(55));
788            assert_eq!(after.idle_nanoseconds, Some(ticks_to_nanoseconds(20)));
789            assert_eq!(after.timestamp_nanoseconds, ticks_to_nanoseconds(175));
790        }
791
792        #[test]
793        fn executor_counters_are_shared_per_executor() {
794            let first = ExecutorCounters::get(usize::MAX - 1);
795            let second = ExecutorCounters::get(usize::MAX - 1);
796            let other = ExecutorCounters::get(usize::MAX - 2);
797            assert!(core::ptr::eq(first, second));
798            assert!(!core::ptr::eq(first, other));
799            assert_eq!(first.executor(), usize::MAX - 1);
800        }
801
802        #[test]
803        fn measured_idle_runs_the_wait() {
804            let executor = alloc::boxed::Box::leak(alloc::boxed::Box::new(
805                embassy_executor::raw::Executor::new(core::ptr::null_mut()),
806            ));
807            let spawner = executor.spawner();
808            let activity = ExecutorActivity::new(spawner);
809            let counters = ExecutorCounters::get(spawner.executor_id());
810            assert!(counters.sample(0).idle_nanoseconds.is_some());
811            assert_eq!(activity.measure_idle(|| 42), 42);
812            let sample = counters.sample(0);
813            assert!(sample.idle_nanoseconds.is_some());
814            assert_eq!(sample.executor, spawner.executor_id());
815        }
816
817        #[test]
818        fn tick_conversion_saturates() {
819            assert_eq!(ticks_to_nanoseconds(0), 0);
820            assert_eq!(ticks_to_nanoseconds(TICK_HERTZ), 1_000_000_000);
821            assert_eq!(ticks_to_nanoseconds(u64::MAX), u64::MAX);
822        }
823
824        /// At 32,768 Hz a tick is 1953125 / 64 ns, so the rounding pattern
825        /// repeats every 64 ticks: these ranges cover every case.
826        #[test]
827        fn differences_of_32768_hertz_conversions_exceed_by_at_most_one_nanosecond() {
828            const HERTZ: u64 = 32_768;
829            let mut exceeded = false;
830            for offset in [0, 1 << 40] {
831                for start in offset..offset + 128 {
832                    assert!(convert(start + 1, HERTZ) > convert(start, HERTZ));
833                    for ticks in 0..128 {
834                        let difference = convert(start + ticks, HERTZ) - convert(start, HERTZ);
835                        let exact = convert(ticks, HERTZ);
836                        assert!(
837                            difference == exact || difference == exact + 1,
838                            "{start} + {ticks}"
839                        );
840                        exceeded |= difference > exact;
841                    }
842                }
843            }
844            assert!(exceeded);
845            // The same tick count can differ by 1 ns: one tick of idle time
846            // from 1 to 2 measures 30,518 ns, one tick of timestamp from 0 to
847            // 1 measures 30,517 ns. Consumers subtract with saturation.
848            assert_eq!(convert(2, HERTZ) - convert(1, HERTZ), 30_518);
849            assert_eq!(convert(1, HERTZ) - convert(0, HERTZ), 30_517);
850            assert_eq!(convert(HERTZ, HERTZ), 1_000_000_000);
851        }
852
853        #[test]
854        fn readers_never_observe_torn_counters() {
855            extern crate std;
856            use portable_atomic::AtomicBool;
857            static COUNTERS: TaskCounters = TaskCounters::new();
858            static DONE: AtomicBool = AtomicBool::new(false);
859            // Steps cross the 32-bit boundary often, so a torn read would
860            // break the busy = polls * step invariant.
861            const STEP: u64 = (1 << 31) + 1;
862            let writer = std::thread::spawn(|| {
863                for _ in 0..200_000 {
864                    COUNTERS.record_poll(STEP);
865                }
866                DONE.store(true, Ordering::Release);
867            });
868            let mut previous = 0;
869            while !DONE.load(Ordering::Acquire) {
870                let sample = COUNTERS.sample();
871                assert_eq!(sample.busy, sample.polls * STEP);
872                assert!(sample.polls >= previous);
873                previous = sample.polls;
874            }
875            writer.join().unwrap();
876            assert_eq!(COUNTERS.sample().polls, 200_000);
877        }
878
879        /// Time a reader may extrapolate past the writer's final value: none
880        /// on x86, whose fences order clock reads; up to the store latency on
881        /// weakly ordered hosts.
882        const EXTRAPOLATION_TOLERANCE: u64 = if cfg!(target_arch = "x86_64") {
883            0
884        } else {
885            10_000
886        };
887
888        /// Regression test: a reader sampling while the executor's thread
889        /// alternates polls and waits must never see busy or idle time
890        /// decrease. Before the clock was read inside the write section, this
891        /// failed in about nine runs out of ten.
892        #[test]
893        fn executor_samples_never_decrease_while_written() {
894            extern crate std;
895            use portable_atomic::AtomicBool;
896            const ITERATIONS: usize = 1_000_000;
897            static COUNTERS: ExecutorCounters = ExecutorCounters::new(42, 0);
898            static DONE: AtomicBool = AtomicBool::new(false);
899            let writer = std::thread::spawn(|| {
900                for _ in 0..ITERATIONS {
901                    COUNTERS.begin_poll();
902                    COUNTERS.end_period();
903                    COUNTERS.begin(STATE_IDLE, now);
904                    COUNTERS.end_period();
905                }
906                DONE.store(true, Ordering::Release);
907            });
908            let mut previous = COUNTERS.sample(0);
909            let mut decreases = 0_u64;
910            while !DONE.load(Ordering::Acquire) {
911                let sample = COUNTERS.sample(0);
912                if sample.busy_nanoseconds < previous.busy_nanoseconds
913                    || sample.idle_nanoseconds.unwrap_or(0) < previous.idle_nanoseconds.unwrap_or(0)
914                    || sample.timestamp_nanoseconds < previous.timestamp_nanoseconds
915                {
916                    decreases += 1;
917                }
918                let accounted = sample.busy_nanoseconds + sample.idle_nanoseconds.unwrap_or(0);
919                assert!(
920                    accounted <= sample.timestamp_nanoseconds + EXTRAPOLATION_TOLERANCE,
921                    "{sample:?}"
922                );
923                previous = sample;
924            }
925            writer.join().unwrap();
926            assert_eq!(decreases, 0, "samples decreased {decreases} times");
927            assert_eq!(COUNTERS.sample(0).polls, ITERATIONS as u64);
928        }
929    }
930}
931
932#[cfg(all(test, not(feature = "metrics")))]
933mod tests {
934    use super::*;
935
936    #[test]
937    fn disabled_hook_only_runs_the_wait() {
938        const { assert!(!ENABLED) };
939        assert_eq!(core::mem::size_of::<ExecutorActivity>(), 0);
940        let executor = alloc::boxed::Box::leak(alloc::boxed::Box::new(
941            embassy_executor::raw::Executor::new(core::ptr::null_mut()),
942        ));
943        assert_eq!(
944            ExecutorActivity::new(executor.spawner()).measure_idle(|| 42),
945            42
946        );
947    }
948}