Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Add per-window frame-duration and present-interval histograms (#61871)
Richard Feldman9e236090b9a3
diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.tomlindex de7e1b57720..0b833fef9f9 100644--- a/crates/gpui/Cargo.toml+++ b/crates/gpui/Cargo.toml@@ -38,6 +38,7 @@ screen-capture = []windows-manifest = ["dep:embed-resource"]input-latency-histogram = ["dep:hdrhistogram"]+frame-duration-histogram = ["dep:hdrhistogram"]profiler = [][lib]diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rsindex 3b766526462..bb0412a0777 100644--- a/crates/gpui/src/window.rs+++ b/crates/gpui/src/window.rs@@ -30,7 +30,10 @@ use futures::FutureExt;use futures::channel::oneshot;use gpui_util::post_inc;use gpui_util::{ResultExt, measure};-#[cfg(feature = "input-latency-histogram")]+#[cfg(any(+ feature = "input-latency-histogram",+ feature = "frame-duration-histogram"+))]use hdrhistogram::Histogram;use itertools::FoldWhile::{Continue, Done};use itertools::Itertools;@@ -1159,6 +1162,8 @@ pub struct Window {pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,#[cfg(feature = "input-latency-histogram")]input_latency_tracker: InputLatencyTracker,+ #[cfg(feature = "frame-duration-histogram")]+ frame_duration_tracker: FrameDurationTracker,last_input_modality: InputModality,pub(crate) refreshing: bool,pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,@@ -1314,6 +1319,99 @@ impl InputLatencyTracker {}}+/// A point-in-time snapshot of the frame-duration histograms for a window,+/// suitable for external formatting.+#[cfg(feature = "frame-duration-histogram")]+#[derive(Clone)]+pub struct FrameDurationSnapshot {+ /// Histogram of `Window::draw` durations, in nanoseconds.+ pub draw_duration_histogram: Histogram<u64>,+ /// Histogram of intervals between consecutively presented frames while the+ /// window was animating, in nanoseconds.+ pub present_interval_histogram: Histogram<u64>,+}++/// Records how long the window takes to produce frames: the duration of every+/// draw, and the interval between consecutive presents while the window is+/// animating (a next-frame callback was already scheduled when the previous+/// frame was presented, so frames are being produced back-to-back and a+/// stretched interval means frames were missed).+///+/// Present intervals are only recorded while the window is active: inactive+/// windows are deliberately throttled to a lower frame rate, which would be+/// indistinguishable from missed frames.+#[cfg(feature = "frame-duration-histogram")]+struct FrameDurationTracker {+ /// Histogram of `Window::draw` durations, in nanoseconds.+ draw_duration_histogram: Histogram<u64>,+ /// Histogram of intervals between consecutively presented frames while the+ /// window was animating, in nanoseconds.+ present_interval_histogram: Histogram<u64>,+ /// When the window last presented a newly drawn frame.+ last_present_at: Option<Instant>,+ /// Whether the window was animating (and active) when the last frame was+ /// presented, making the interval ending at the next present meaningful.+ animating_at_last_present: bool,+ /// Whether `Window::draw` ran since the last present. Distinguishes+ /// presents of new frames from re-presents of an unchanged frame (e.g.+ /// to sustain the display's refresh rate during high-rate input).+ drew_since_last_present: bool,+}++#[cfg(feature = "frame-duration-histogram")]+impl FrameDurationTracker {+ fn new() -> Result<Self> {+ Ok(Self {+ draw_duration_histogram: Histogram::new(3)+ .map_err(|e| anyhow!("Failed to create draw duration histogram: {e}"))?,+ present_interval_histogram: Histogram::new(3)+ .map_err(|e| anyhow!("Failed to create present interval histogram: {e}"))?,+ last_present_at: None,+ animating_at_last_present: false,+ drew_since_last_present: false,+ })+ }++ fn record_draw(&mut self, duration: Duration) {+ self.draw_duration_histogram+ .record(duration.as_nanos() as u64)+ .ok();+ self.drew_since_last_present = true;+ }++ /// Record that a frame was presented. `next_frame_scheduled` reports+ /// whether a next-frame callback is already pending, which is what marks+ /// the window as animating for the interval ending at the *next* present.+ fn record_present(+ &mut self,+ presented_at: Instant,+ window_active: bool,+ next_frame_scheduled: bool,+ ) {+ if !mem::take(&mut self.drew_since_last_present) {+ // Re-presenting an unchanged frame; not a new frame for interval+ // purposes.+ return;+ }+ if self.animating_at_last_present+ && window_active+ && let Some(last_present_at) = self.last_present_at+ {+ let interval_nanos = presented_at.duration_since(last_present_at).as_nanos() as u64;+ self.present_interval_histogram.record(interval_nanos).ok();+ }+ self.last_present_at = Some(presented_at);+ self.animating_at_last_present = next_frame_scheduled && window_active;+ }++ fn snapshot(&self) -> FrameDurationSnapshot {+ FrameDurationSnapshot {+ draw_duration_histogram: self.draw_duration_histogram.clone(),+ present_interval_histogram: self.present_interval_histogram.clone(),+ }+ }+}+#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub(crate) enum DrawPhase {None,@@ -1922,6 +2020,8 @@ impl Window {input_rate_tracker,#[cfg(feature = "input-latency-histogram")]input_latency_tracker: InputLatencyTracker::new()?,+ #[cfg(feature = "frame-duration-histogram")]+ frame_duration_tracker: FrameDurationTracker::new()?,last_input_modality: InputModality::Mouse,refreshing: false,activation_observers: SubscriberSet::new(),@@ -2877,6 +2977,9 @@ impl Window {// Drain unconditionally so a stale first-invalidation timestamp can't// leak into a later frame across enable/disable of frame tracing.let frame_dirty = self.invalidator.take_frame_dirty();+ #[cfg(feature = "frame-duration-histogram")]+ let draw_started_at = Some(Instant::now());+ #[cfg(not(feature = "frame-duration-histogram"))]let draw_started_at = profiler::frame_trace_enabled().then(Instant::now);// Set up the per-App arena for element allocation during this draw.@@ -2986,12 +3089,16 @@ impl Window {self.needs_present.set(true);if let Some(draw_start) = draw_started_at {+ let draw_end = Instant::now();+ #[cfg(feature = "frame-duration-histogram")]+ self.frame_duration_tracker+ .record_draw(draw_end.duration_since(draw_start));profiler::record_frame_timing(profiler::FrameTiming {window_id: self.handle.window_id(),dirty_at: frame_dirty.dirty_at,invalidations: frame_dirty.invalidations,draw_start,- draw_end: Instant::now(),+ draw_end,});}@@ -3027,6 +3134,15 @@ impl Window {self.platform_window.draw(&self.rendered_frame.scene);#[cfg(feature = "input-latency-histogram")]self.input_latency_tracker.record_frame_presented();+ #[cfg(feature = "frame-duration-histogram")]+ {+ let next_frame_scheduled = !self.next_frame_callbacks.borrow().is_empty();+ self.frame_duration_tracker.record_present(+ Instant::now(),+ self.active.get(),+ next_frame_scheduled,+ );+ }self.needs_present.set(false);profiling::finish_frame!();}@@ -3049,6 +3165,12 @@ impl Window {self.input_latency_tracker.snapshot()}+ /// Returns a snapshot of the current frame-duration histograms.+ #[cfg(feature = "frame-duration-histogram")]+ pub fn frame_duration_snapshot(&self) -> FrameDurationSnapshot {+ self.frame_duration_tracker.snapshot()+ }+fn draw_roots(&mut self, cx: &mut App) {self.invalidator.set_phase(DrawPhase::Prepaint);self.tooltip_bounds.take();@@ -7453,4 +7575,105 @@ mod tests {.unwrap();assert_eq!(b_focus_count.get(), 1);}++ #[cfg(feature = "frame-duration-histogram")]+ mod frame_duration_tracker {+ use crate::window::FrameDurationTracker;+ use scheduler::Instant;+ use std::time::Duration;++ const FRAME: Duration = Duration::from_millis(16);++ fn draw_and_present(+ tracker: &mut FrameDurationTracker,+ presented_at: Instant,+ window_active: bool,+ next_frame_scheduled: bool,+ ) {+ tracker.record_draw(Duration::from_millis(2));+ tracker.record_present(presented_at, window_active, next_frame_scheduled);+ }++ #[test]+ fn records_intervals_only_between_animation_frames() {+ let mut tracker = FrameDurationTracker::new().unwrap();+ let start = Instant::now();++ // The first frame has nothing to measure an interval against.+ draw_and_present(&mut tracker, start, true, true);+ assert_eq!(tracker.present_interval_histogram.len(), 0);++ draw_and_present(&mut tracker, start + FRAME, true, true);+ assert_eq!(tracker.present_interval_histogram.len(), 1);++ // The animation ends here: no next frame was scheduled when this+ // frame was presented.+ draw_and_present(&mut tracker, start + FRAME * 2, true, false);+ assert_eq!(tracker.present_interval_histogram.len(), 2);++ // The window sat idle before an input-driven frame; the gap is not+ // an animation interval.+ draw_and_present(&mut tracker, start + FRAME * 100, true, true);+ assert_eq!(tracker.present_interval_histogram.len(), 2);+ }++ #[test]+ fn missed_frames_stretch_the_recorded_interval() {+ let mut tracker = FrameDurationTracker::new().unwrap();+ let start = Instant::now();++ draw_and_present(&mut tracker, start, true, true);+ draw_and_present(&mut tracker, start + FRAME * 5, true, true);++ let recorded = tracker.present_interval_histogram.max();+ assert!(recorded >= (FRAME * 4).as_nanos() as u64);+ }++ #[test]+ fn ignores_re_presents_of_unchanged_frames() {+ let mut tracker = FrameDurationTracker::new().unwrap();+ let start = Instant::now();++ draw_and_present(&mut tracker, start, true, true);+ // A present without a draw (e.g. sustaining the display's refresh+ // rate) must neither count as a frame nor shift the interval+ // baseline.+ tracker.record_present(start + FRAME / 2, true, true);+ draw_and_present(&mut tracker, start + FRAME, true, true);++ assert_eq!(tracker.present_interval_histogram.len(), 1);+ // The interval spans from the drawn frame, not the re-present.+ assert!(tracker.present_interval_histogram.max() >= (FRAME * 3 / 4).as_nanos() as u64);+ }++ #[test]+ fn skips_intervals_for_inactive_windows() {+ let mut tracker = FrameDurationTracker::new().unwrap();+ let start = Instant::now();++ draw_and_present(&mut tracker, start, false, true);+ draw_and_present(&mut tracker, start + FRAME, false, true);+ assert_eq!(tracker.present_interval_histogram.len(), 0);++ // The first interval after reactivation began while the window was+ // inactive (and possibly throttled), so it is also skipped.+ draw_and_present(&mut tracker, start + FRAME * 2, true, true);+ assert_eq!(tracker.present_interval_histogram.len(), 0);++ draw_and_present(&mut tracker, start + FRAME * 3, true, true);+ assert_eq!(tracker.present_interval_histogram.len(), 1);+ }++ #[test]+ fn records_every_draw_duration() {+ let mut tracker = FrameDurationTracker::new().unwrap();++ tracker.record_draw(Duration::from_millis(2));+ tracker.record_draw(Duration::from_millis(40));++ let snapshot = tracker.snapshot();+ assert_eq!(snapshot.draw_duration_histogram.len(), 2);+ assert!(snapshot.draw_duration_histogram.max() >= 39_000_000);+ }+ }}diff --git a/crates/input_latency_ui/Cargo.toml b/crates/input_latency_ui/Cargo.tomlindex 3d5387636ed..3dd19e08beb 100644--- a/crates/input_latency_ui/Cargo.toml+++ b/crates/input_latency_ui/Cargo.toml@@ -14,6 +14,9 @@ path = "src/input_latency_ui.rs"[dependencies]chrono.workspace = truecollections.workspace = true-gpui = { workspace = true, features = ["input-latency-histogram"] }+gpui = { workspace = true, features = [+ "frame-duration-histogram",+ "input-latency-histogram",+] }hdrhistogram.workspace = truetelemetry.workspace = truediff --git a/crates/input_latency_ui/src/input_latency_ui.rs b/crates/input_latency_ui/src/input_latency_ui.rsindex 4054c6b3c0c..e63afd288a6 100644--- a/crates/input_latency_ui/src/input_latency_ui.rs+++ b/crates/input_latency_ui/src/input_latency_ui.rs@@ -1,5 +1,5 @@-use collections::HashMap;-use gpui::{App, Global, InputLatencySnapshot, Window, WindowId, actions};+use collections::{HashMap, HashSet};+use gpui::{App, FrameDurationSnapshot, Global, InputLatencySnapshot, Window, WindowId, actions};use hdrhistogram::Histogram;use std::time::Instant;@@ -102,7 +102,11 @@ pub fn report_input_latency_telemetry(window: &Window, cx: &mut App) {let current = window.input_latency_snapshot();let window_id = window.window_handle().window_id();+ let open_window_ids = open_window_ids(cx);let state = cx.default_global::<TelemetryReporterState>();+ state+ .previous+ .retain(|window_id, _| open_window_ids.contains(window_id));let now = Instant::now();let (delta_latency, delta_coalesce, report_window_seconds) =@@ -163,6 +167,114 @@ pub fn report_input_latency_telemetry(window: &Window, cx: &mut App) {);}+/// Per-window baselines for frame-duration telemetry, keyed by window id. Kept+/// separate from the input-latency baselines so the two reports never share+/// state.+#[derive(Default)]+struct FrameDurationTelemetryState {+ previous: HashMap<WindowId, (Instant, FrameDurationSnapshot)>,+}++impl Global for FrameDurationTelemetryState {}++/// Nanosecond boundaries for the present-interval buckets used in telemetry:+/// roughly the 120Hz, 60Hz, and 30Hz frame budgets, with headroom for jitter.+const MS9_NS: u64 = 9_000_000;+const MS18_NS: u64 = 18_000_000;+const MS36_NS: u64 = 36_000_000;++/// Minimum number of draws that must be present in the delta window for the+/// frame-duration report to be sent. Avoids sending noise for windows that are+/// mostly idle.+const MIN_DRAWS_TO_REPORT: u64 = 1_000;++/// Computes and sends a `Frame Duration Report` telemetry event for the given+/// window if enough frames were drawn since the last report.+///+/// The report contains bucketed draw durations (how long `Window::draw` took)+/// and bucketed present intervals (the achieved frame-to-frame cadence while+/// the window was animating), so missed frames are visible in the fleet even+/// when no input was involved.+///+/// Call this periodically (e.g. every five minutes) from a spawned task.+pub fn report_frame_duration_telemetry(window: &Window, cx: &mut App) {+ let current = window.frame_duration_snapshot();+ let window_id = window.window_handle().window_id();++ let open_window_ids = open_window_ids(cx);+ let state = cx.default_global::<FrameDurationTelemetryState>();+ state+ .previous+ .retain(|window_id, _| open_window_ids.contains(window_id));+ let now = Instant::now();++ let (delta_draws, delta_intervals, report_window_seconds) =+ if let Some((prev_instant, prev_snapshot)) = state.previous.get(&window_id) {+ let mut delta_draws = current.draw_duration_histogram.clone();+ delta_draws+ .subtract(&prev_snapshot.draw_duration_histogram)+ .ok();+ let mut delta_intervals = current.present_interval_histogram.clone();+ delta_intervals+ .subtract(&prev_snapshot.present_interval_histogram)+ .ok();+ let elapsed = now.duration_since(*prev_instant).as_secs();+ (delta_draws, delta_intervals, elapsed)+ } else {+ // First report for this window: the full cumulative histograms are+ // the delta from the empty starting state. We don't know how long+ // the window has been open, so record 0 to signal that this is the+ // initial accumulation period rather than a fixed-width window.+ (+ current.draw_duration_histogram.clone(),+ current.present_interval_histogram.clone(),+ 0u64,+ )+ };++ let total_draws = delta_draws.len();+ if total_draws < MIN_DRAWS_TO_REPORT {+ return;+ }++ state.previous.insert(window_id, (now, current));++ let draws_sub4 = count_frames_in_range(&delta_draws, 0, MS4_NS);+ let draws_4to8 = count_frames_in_range(&delta_draws, MS4_NS, MS8_NS);+ let draws_8to16 = count_frames_in_range(&delta_draws, MS8_NS, MS16_NS);+ let draws_16to33 = count_frames_in_range(&delta_draws, MS16_NS, MS33_NS);+ // draws > 33ms are implicitly total_draws - (sub4 + 4to8 + 8to16 + 16to33)++ let total_intervals = delta_intervals.len();+ let intervals_sub9 = count_frames_in_range(&delta_intervals, 0, MS9_NS);+ let intervals_9to18 = count_frames_in_range(&delta_intervals, MS9_NS, MS18_NS);+ let intervals_18to36 = count_frames_in_range(&delta_intervals, MS18_NS, MS36_NS);+ let intervals_36to100 = count_frames_in_range(&delta_intervals, MS36_NS, MS100_NS);+ // intervals > 100ms are implicitly total_intervals - (the buckets above)++ telemetry::event!(+ "Frame Duration Report",+ draws_sub4 = draws_sub4,+ draws_4to8 = draws_4to8,+ draws_8to16 = draws_8to16,+ draws_16to33 = draws_16to33,+ total_draws = total_draws,+ intervals_sub9 = intervals_sub9,+ intervals_9to18 = intervals_9to18,+ intervals_18to36 = intervals_18to36,+ intervals_36to100 = intervals_36to100,+ total_intervals = total_intervals,+ report_window_seconds = report_window_seconds,+ );+}++fn open_window_ids(cx: &App) -> HashSet<WindowId> {+ cx.windows()+ .into_iter()+ .map(|window| window.window_id())+ .collect()+}+fn count_frames_in_range(histogram: &Histogram<u64>, low_ns: u64, high_ns: u64) -> u64 {histogram.iter_recorded()diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.tomlindex 81aee983dda..3d2f97b61a3 100644--- a/crates/zed/Cargo.toml+++ b/crates/zed/Cargo.toml@@ -118,7 +118,11 @@ git_ui = { workspace = true, features = ["call"] }git_ui_core.workspace = truego_to_line.workspace = truesystem_specs.workspace = true-gpui = { workspace = true, features = ["input-latency-histogram", "profiler"] }+gpui = { workspace = true, features = [+ "frame-duration-histogram",+ "input-latency-histogram",+ "profiler",+] }gpui_platform = {workspace = true, features=["screen-capture", "font-kit", "wayland", "x11"]}hdrhistogram.workspace = trueimage = { workspace = true, optional = true }diff --git a/crates/zed/src/zed.rs b/crates/zed/src/zed.rsindex 1b5434efe7c..be34bda080e 100644--- a/crates/zed/src/zed.rs+++ b/crates/zed/src/zed.rs@@ -480,6 +480,7 @@ pub fn initialize_workspace(app_state: Arc<AppState>, cx: &mut App) {if cx.update(|window, cx| {input_latency_ui::report_input_latency_telemetry(window, cx);+ input_latency_ui::report_frame_duration_telemetry(window, cx);}).is_err(){