Skip to main content

tokio/runtime/scheduler/multi_thread/
stats.rs

1use crate::runtime::metrics::ScheduleLatencyContext;
2use crate::runtime::{Config, MetricsBatch, WorkerMetrics};
3
4use std::time::{Duration, Instant};
5
6/// Per-worker statistics. This is used for both tuning the scheduler and
7/// reporting runtime-level metrics/stats.
8pub(crate) struct Stats {
9    /// The metrics batch used to report runtime-level metrics/stats to the
10    /// user.
11    batch: MetricsBatch,
12
13    /// Instant at which work last resumed (continued after park).
14    ///
15    /// This duplicates the value stored in `MetricsBatch`. We will unify
16    /// `Stats` and `MetricsBatch` when we stabilize metrics.
17    processing_scheduled_tasks_started_at: Instant,
18
19    /// Number of tasks polled in the batch of scheduled tasks
20    tasks_polled_in_batch: usize,
21
22    /// Exponentially-weighted moving average of time spent polling scheduled a
23    /// task.
24    ///
25    /// Tracked in nanoseconds, stored as a `f64` since that is what we use with
26    /// the EWMA calculations
27    task_poll_time_ewma: f64,
28}
29
30/// How to weigh each individual poll time, value is plucked from thin air.
31const TASK_POLL_TIME_EWMA_ALPHA: f64 = 0.1;
32
33/// Ideally, we wouldn't go above this, value is plucked from thin air.
34const TARGET_GLOBAL_QUEUE_INTERVAL: f64 = Duration::from_micros(200).as_nanos() as f64;
35
36/// Max value for the global queue interval. This is 2x the previous default
37const MAX_TASKS_POLLED_PER_GLOBAL_QUEUE_INTERVAL: u32 = 127;
38
39/// This is the previous default
40const TARGET_TASKS_POLLED_PER_GLOBAL_QUEUE_INTERVAL: u32 = 61;
41
42impl Stats {
43    pub(crate) fn new(worker_metrics: &WorkerMetrics) -> Stats {
44        // Seed the value with what we hope to see.
45        let task_poll_time_ewma =
46            TARGET_GLOBAL_QUEUE_INTERVAL / TARGET_TASKS_POLLED_PER_GLOBAL_QUEUE_INTERVAL as f64;
47
48        Stats {
49            batch: MetricsBatch::new(worker_metrics),
50            processing_scheduled_tasks_started_at: Instant::now(),
51            tasks_polled_in_batch: 0,
52            task_poll_time_ewma,
53        }
54    }
55
56    pub(crate) fn tuned_global_queue_interval(&self, config: &Config) -> u32 {
57        // If an interval is explicitly set, don't tune.
58        if let Some(configured) = config.global_queue_interval {
59            return configured;
60        }
61
62        // As of Rust 1.45, casts from f64 -> u32 are saturating, which is fine here.
63        let tasks_per_interval = (TARGET_GLOBAL_QUEUE_INTERVAL / self.task_poll_time_ewma) as u32;
64
65        // If we are using self-tuning, we don't want to return less than 2 as that would result in the
66        // global queue always getting checked first.
67        tasks_per_interval.clamp(2, MAX_TASKS_POLLED_PER_GLOBAL_QUEUE_INTERVAL)
68    }
69
70    pub(crate) fn submit(&mut self, to: &WorkerMetrics) {
71        self.batch.submit(to, self.task_poll_time_ewma as u64);
72    }
73
74    pub(crate) fn about_to_park(&mut self) {
75        self.batch.about_to_park();
76    }
77
78    pub(crate) fn unparked(&mut self) {
79        self.batch.unparked();
80    }
81
82    pub(crate) fn inc_local_schedule_count(&mut self) {
83        self.batch.inc_local_schedule_count();
84    }
85
86    pub(crate) fn start_processing_scheduled_tasks(&mut self) {
87        self.batch.start_processing_scheduled_tasks();
88
89        self.processing_scheduled_tasks_started_at = Instant::now();
90        self.tasks_polled_in_batch = 0;
91    }
92
93    pub(crate) fn end_processing_scheduled_tasks(&mut self) {
94        self.batch.end_processing_scheduled_tasks();
95
96        // Update the EWMA task poll time
97        if self.tasks_polled_in_batch > 0 {
98            let now = Instant::now();
99
100            // If we "overflow" this conversion, we have bigger problems than
101            // slightly off stats.
102            let elapsed = (now - self.processing_scheduled_tasks_started_at).as_nanos() as f64;
103            let num_polls = self.tasks_polled_in_batch as f64;
104
105            // Calculate the mean poll duration for a single task in the batch
106            let mean_poll_duration = elapsed / num_polls;
107
108            // Compute the alpha weighted by the number of tasks polled this batch.
109            let weighted_alpha = 1.0 - (1.0 - TASK_POLL_TIME_EWMA_ALPHA).powf(num_polls);
110
111            // Now compute the new weighted average task poll time.
112            self.task_poll_time_ewma = weighted_alpha * mean_poll_duration
113                + (1.0 - weighted_alpha) * self.task_poll_time_ewma;
114        }
115    }
116
117    pub(crate) fn start_poll(&mut self, task_scheduled_at: Option<ScheduleLatencyContext>) {
118        self.batch.start_poll(task_scheduled_at);
119
120        self.tasks_polled_in_batch += 1;
121    }
122
123    pub(crate) fn end_poll(&mut self) {
124        self.batch.end_poll();
125    }
126
127    pub(crate) fn incr_steal_count(&mut self, by: u16) {
128        self.batch.incr_steal_count(by);
129    }
130
131    pub(crate) fn incr_steal_operations(&mut self) {
132        self.batch.incr_steal_operations();
133    }
134
135    pub(crate) fn incr_overflow_count(&mut self) {
136        self.batch.incr_overflow_count();
137    }
138}