Skip to main content

Module metrics

Module metrics 

Source
Expand description

Portable CPU activity metrics for tasks and executors (metrics feature).

Every poll of a managed task is timed with a monotonic clock: the operating system’s monotonic clock on Linux, macOS and Windows, and Embassy’s clock, which each platform already provides for sleep, everywhere else. The clock is read twice per poll; nothing is allocated on the poll path. Per-task counters live beside the task storage slots and per-executor counters are created once per executor, so spawning allocates nothing more either.

On Linux, macOS and Windows the metrics clock counts from its own first read, not from embassy_time::Instant’s origin: compare metrics timestamps only with each other.

Without the feature, Manager::get_metrics returns None and ExecutorActivity::measure_idle only runs its closure, so platforms and applications can use the API unconditionally at no cost.

§What is measured

Busy time is wall-clock time spent inside task polls, not processor time: on hosts, time the thread is descheduled or blocked during a poll counts as busy. Durations are rounded to the clock’s resolution (TICK_HERTZ). With a coarse clock, such as a 32,768 Hz real-time counter, each poll is measured as a whole number of ticks; as polls start at uncorrelated phases, totals over many polls remain unbiased.

Interrupt handlers that run during a task poll count as that task’s busy time; those that run while the executor waits count as idle time.

§Computing loads

Every reported counter and executor timestamp never decreases. Consumers sample Manager::get_metrics periodically and divide differences between two snapshots, computed with saturating_sub:

  • Match executors between snapshots by ExecutorMetrics::executor, not by ExecutorMetrics::spawner: an executor is reported under its lowest spawner registration, which can change.
  • An executor’s load over the window is Δbusy / Δtimestamp with that executor’s own ExecutorMetrics::timestamp_nanoseconds. When ExecutorMetrics::idle_nanoseconds is available on both sides, prefer 1 − Δidle / Δtimestamp: it also counts executor bookkeeping and foreign work on that core as load. Both include the poll or wait in progress, so they are continuous. They are close to, but not strictly within, [0, 1]: clamp them (see Precision).
  • A task’s share is Δbusy / ΔMetricsSnapshot::timestamp_nanoseconds. Task busy time is added when a poll ends, so a long poll counts entirely in the window where it ends, and the shares of one executor’s tasks can then sum above 1. Normalise per executor, grouping tasks by TaskMetrics::executor: when their sum exceeds 1, divide each of them by that sum rather than clamping each task separately. Compare TaskMetrics::generation to detect a reused task identifier.
  • Tasks adopted rather than spawned by the manager have no counters, report zero polls, have spawner == usize::MAX and no executor.

§Precision

Counters are kept in clock ticks and each one is converted to nanoseconds separately, rounding down. When TICK_HERTZ does not divide one billion, as with a 32,768 Hz counter, the difference of two converted values can exceed the converted difference by 1 ns, so Δidle can exceed Δtimestamp by 1 ns over the same ticks. On multi-core targets, a reader can also extrapolate a period in progress slightly past the value its writer finally stores (see Concurrency); the excess is kept rather than reported as a decrease. Use saturating_sub for every difference and clamp ratios to [0, 1].

§Platform hook

Executor busy time is derived from task polls and needs no platform code. Idle time, the time an executor waits for work, can only be measured by the executor loop. Platforms create an ExecutorActivity on the executor’s thread before its loop, and wrap their wait with ExecutorActivity::measure_idle, between polls of their executor:

ⓘ
let activity = task::metrics::ExecutorActivity::new(executor.spawner());
loop {
    unsafe { executor.poll() };
    activity.measure_idle(|| cortex_m::asm::wfe());
}

Once an executor’s hook exists, its ExecutorMetrics::idle_nanoseconds is Some, starting at 0; without the hook, it is None. The hook is !Send, like the Spawner it is created from:

ⓘ
fn assert_send<T: Send>() {}
assert_send::<task::metrics::ExecutorActivity>();

§Concurrency

Each executor’s counters have a single writer, the executor’s own thread: task polls and ExecutorActivity::measure_idle, whose handle cannot leave its thread. Readers use a sequence lock built from 32-bit atomic loads and stores, so it works without compare-and-swap or 64-bit atomics, and they spin while a write is in progress, outside any critical section. Never read the counters from code that preempts a writer on the same core: an interrupt handler, or a task of an interrupt executor that preempts an instrumented thread executor. Such a reader would spin forever.

Writers read the clock inside their write section, which keeps a reader from extrapolating a finished period on a single core and on x86. On weakly ordered multi-core architectures, such as AArch64 and RISC-V, fences do not order a system-register clock read after an earlier store, so a reader on another core can still extrapolate a period in progress by up to the writer’s store latency. Reported values never decrease because every reader clamps its sample to a per-executor high-water mark of busy time, idle time and timestamp, updated with plain loads and stores inside a short critical section.

Structs§

ExecutorActivity
Executor idle hook; does nothing without the metrics feature.
ExecutorMetrics
Cumulative counters of one executor (a core or an operating system thread).
MetricsSnapshot
Sample of all task and executor counters. Each task’s and each executor’s counters are read consistently; the set is not one atomic instant.
TaskMetrics
Cumulative counters of one registered task.

Constants§

ENABLED
True when the metrics feature instruments task polls.