Skip to main content

veilid_tools/
yield_timing.rs

1use super::*;
2
3/// Total wall time from enqueue to wakeup at which a yield reports itself
4pub const YIELD_SLOW_LOG_US: u64 = 1_000_000;
5
6/// Wall-clock phases of one closure handed to a worker pool: queue wait, run, and the
7/// gap between the result being ready and the awaiting task being polled again.
8///
9/// The three phases attribute a slow yield to the pool queue, the closure itself, or the
10/// executor. A long stall in every phase at once means the process was not being run.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct YieldTiming {
13    /// Microseconds when the closure was handed to the pool
14    pub enqueued_us: u64,
15    /// Microseconds when a pool thread began running it
16    pub started_us: u64,
17    /// Microseconds when it returned
18    pub finished_us: u64,
19    /// Microseconds when the awaiting task observed the result
20    pub woken_us: u64,
21}
22
23impl YieldTiming {
24    /// Time spent waiting in the pool queue
25    #[must_use]
26    pub fn wait_us(&self) -> u64 {
27        self.started_us.saturating_sub(self.enqueued_us)
28    }
29    /// Time the closure ran
30    #[must_use]
31    pub fn run_us(&self) -> u64 {
32        self.finished_us.saturating_sub(self.started_us)
33    }
34    /// Time between the result being ready and the awaiting task resuming
35    #[must_use]
36    pub fn wake_us(&self) -> u64 {
37        self.woken_us.saturating_sub(self.finished_us)
38    }
39    /// Enqueue to wakeup
40    #[must_use]
41    pub fn total_us(&self) -> u64 {
42        self.woken_us.saturating_sub(self.enqueued_us)
43    }
44    /// Whether the total crosses the reporting floor
45    #[must_use]
46    pub fn is_slow(&self) -> bool {
47        self.total_us() >= YIELD_SLOW_LOG_US
48    }
49    /// Log a bare executor yield (no pool) whose wakeup took at least the reporting floor
50    pub fn log_inline_yield_if_slow(yielded_us: u64, woken_us: u64) {
51        let wake_us = woken_us.saturating_sub(yielded_us);
52        if wake_us >= YIELD_SLOW_LOG_US {
53            debug!("yield slow (inline): wake {}", human_duration(wake_us));
54        }
55    }
56    /// Log the phase split when slow; `depth` is the pool's queue depth at enqueue, for
57    /// pools that expose one
58    pub fn log_if_slow(&self, pool: &str, depth: Option<usize>) {
59        if !self.is_slow() {
60            return;
61        }
62        let depth = depth.map_or_else(String::new, |d| format!(" (queue depth {})", d));
63        debug!(
64            "yield slow ({}): wait {} run {} wake {}{}",
65            pool,
66            human_duration(self.wait_us()),
67            human_duration(self.run_us()),
68            human_duration(self.wake_us()),
69            depth
70        );
71    }
72}