Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui: Unify performance tracking under the profiler feature (#62496)

Anthony Eida21007b7a948
diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml
index bc5aab22b3e..f86c16830ff 100644
--- a/crates/gpui/Cargo.toml
+++ b/crates/gpui/Cargo.toml
@@ -26,7 +26,7 @@ test-support = [
"x11",
"proptest",
]
-bench = ["test-support", "dep:criterion", "dep:hdrhistogram"]
+bench = ["test-support", "profiler", "dep:criterion"]
inspector = ["gpui_macros/inspector"]
leak-detection = ["backtrace"]
wayland = []
@@ -37,9 +37,7 @@ screen-capture = [
"scap",
]
windows-manifest = ["dep:embed-resource"]
-input-latency-histogram = ["dep:hdrhistogram"]
-frame-duration-histogram = ["dep:hdrhistogram"]
-profiler = []
+profiler = ["dep:hdrhistogram"]
[lib]
path = "src/gpui.rs"
diff --git a/crates/gpui/src/app/bench_context.rs b/crates/gpui/src/app/bench_context.rs
index 5966f7f80be..7a74bcee1f5 100644
--- a/crates/gpui/src/app/bench_context.rs
+++ b/crates/gpui/src/app/bench_context.rs
@@ -15,7 +15,7 @@ use crate::{
PlatformTextSystem, Render, Reservation, Task, TestPlatform, ThreadedDispatcher, VisualContext,
Window, WindowBounds, WindowHandle, WindowOptions,
app::GpuiBorrow,
- profiler::{self, FrameTiming, FrameTimingCollector},
+ profiler::{self, FrameEvent, FrameTimingCollector},
};
/// Returns a benchmark platform backed by this thread's shared dispatcher.
@@ -93,25 +93,37 @@ impl BenchReport {
}
}
- fn record_frame_timings<'i>(&self, timings: impl IntoIterator<Item = &'i FrameTiming>) {
+ fn record_frame_timings<'i>(&self, events: impl IntoIterator<Item = &'i FrameEvent>) {
let mut snapshot = self.frame_snapshot.borrow_mut();
// `.ok()` on `record`: this operation is infallible (the histograms auto-resize).
- for timing in timings {
- snapshot
- .draw
- .record(timing.draw_duration().as_nanos() as u64)
- .ok();
- if let Some(dirty_to_draw) = timing.dirty_to_draw_duration() {
- snapshot
- .dirty_to_draw
- .record(dirty_to_draw.as_nanos() as u64)
- .ok();
- }
- if timing.invalidations > 0 {
- snapshot
- .invalidations_per_frame
- .record(timing.invalidations)
- .ok();
+ for event in events {
+ match event {
+ FrameEvent::Draw(timing) => {
+ snapshot
+ .draw
+ .record(timing.draw_duration().as_nanos() as u64)
+ .ok();
+ if let Some(dirty_to_draw) = timing.dirty_to_draw_duration() {
+ snapshot
+ .dirty_to_draw
+ .record(dirty_to_draw.as_nanos() as u64)
+ .ok();
+ }
+ if timing.invalidations > 0 {
+ snapshot
+ .invalidations_per_frame
+ .record(timing.invalidations)
+ .ok();
+ }
+ }
+ FrameEvent::Present(timing) => {
+ if let Some(animation_interval) = timing.animation_interval {
+ snapshot
+ .present_interval
+ .record(animation_interval.as_nanos() as u64)
+ .ok();
+ }
+ }
}
}
}
@@ -152,6 +164,7 @@ impl BenchReport {
eprintln!(" note: includes Criterion warmup/calibration");
self.print_histogram("window dirty-to-draw", &frame_snapshot.dirty_to_draw);
self.print_histogram("window draw", &frame_snapshot.draw);
+ self.print_histogram("window present interval", &frame_snapshot.present_interval);
if !frame_snapshot.invalidations_per_frame.is_empty() {
eprintln!(
" invalidations per frame: mean {:.2}, max {}",
@@ -204,6 +217,7 @@ impl BenchReport {
struct WindowFrameSnapshot {
dirty_to_draw: Histogram<u64>,
draw: Histogram<u64>,
+ present_interval: Histogram<u64>,
invalidations_per_frame: Histogram<u64>,
}
@@ -212,12 +226,13 @@ impl WindowFrameSnapshot {
Self {
dirty_to_draw: Histogram::new(3).expect("3 significant digits is valid"),
draw: Histogram::new(3).expect("3 significant digits is valid"),
+ present_interval: Histogram::new(3).expect("3 significant digits is valid"),
invalidations_per_frame: Histogram::new(3).expect("3 significant digits is valid"),
}
}
fn is_empty(&self) -> bool {
- self.dirty_to_draw.is_empty() && self.draw.is_empty()
+ self.dirty_to_draw.is_empty() && self.draw.is_empty() && self.present_interval.is_empty()
}
}
@@ -225,57 +240,49 @@ fn format_duration(duration: Duration) -> String {
format!("{:.3}ms", duration.as_secs_f64() * 1000.)
}
-/// Enables frame tracing for the duration of a measurement and collects the
-/// frames recorded within it. The previous tracing state is restored on drop,
-/// so a panicking measurement doesn't leave tracing enabled for unrelated code
-/// (e.g. a later benchmark in the same process).
-struct FrameTraceScope {
+/// Enables profiler tracing for a measurement and collects its frame events.
+///
+/// The previous tracing state is restored on drop, so a panicking measurement
+/// doesn't leave tracing enabled for unrelated code such as a later benchmark
+/// in the same process.
+struct TraceScope {
collector: FrameTimingCollector,
- was_already_enabled: bool,
+ _trace_guard: profiler::TraceGuard,
}
-impl FrameTraceScope {
+impl TraceScope {
fn start() -> Self {
- let was_already_enabled = !profiler::set_frame_trace_enabled(true);
+ let trace_guard = profiler::trace_scope();
Self {
collector: FrameTimingCollector::new(),
- was_already_enabled,
+ _trace_guard: trace_guard,
}
}
- fn finish(mut self) -> Vec<FrameTiming> {
+ fn finish(mut self) -> Vec<FrameEvent> {
self.collector.collect_unseen()
- // Dropping `self` restores the previous tracing state.
- }
-}
-
-impl Drop for FrameTraceScope {
- fn drop(&mut self) {
- if !self.was_already_enabled {
- profiler::set_frame_trace_enabled(false);
- }
}
}
struct MeasuredTaskInput<Input> {
input: Input,
- frame_trace_scope: Option<FrameTraceScope>,
+ trace_scope: Option<TraceScope>,
}
struct MeasuredTaskOutput<Output> {
- frame_trace_scope: Option<FrameTraceScope>,
+ trace_scope: Option<TraceScope>,
report: BenchReport,
_output: Output,
}
impl<Output> Drop for MeasuredTaskOutput<Output> {
fn drop(&mut self) {
- let frame_trace_scope = self
- .frame_trace_scope
+ let trace_scope = self
+ .trace_scope
.take()
- .expect("measured task output should retain its frame trace scope");
+ .expect("measured task output should retain its trace scope");
self.report
- .record_frame_timings(frame_trace_scope.finish().iter());
+ .record_frame_timings(trace_scope.finish().iter());
}
}
@@ -460,7 +467,7 @@ impl<'a, 'measurement> BenchAppContext<'a, 'measurement> {
/// benchmark's frame report through the GPUI frame profiler.
pub fn bench_iter(&mut self, mut benchmark: impl FnMut(&mut Self)) {
let bencher = self.take_bencher("bench_iter");
- let collector = FrameTraceScope::start();
+ let collector = TraceScope::start();
let mut benchmark = || benchmark(self);
bencher.iter(&mut benchmark);
self.report.record_frame_timings(collector.finish().iter());
@@ -490,7 +497,7 @@ impl<'a, 'measurement> BenchAppContext<'a, 'measurement> {
/// measured. Both the setup input and task output are dropped after timing
/// stops.
///
- /// Each iteration is kept in its own Criterion batch so frame tracing and
+ /// Each iteration is kept in its own Criterion batch so profiler tracing and
/// destruction cannot overlap adjacent measurements.
pub fn bench_batched_task<Input, Output>(
&mut self,
@@ -525,14 +532,14 @@ impl<'a, 'measurement> BenchAppContext<'a, 'measurement> {
setup_context.settle();
MeasuredTaskInput {
input: setup(&mut setup_context),
- frame_trace_scope: Some(FrameTraceScope::start()),
+ trace_scope: Some(TraceScope::start()),
}
},
|measured_input| {
let task = benchmark(&mut measured_input.input, &mut benchmark_context);
let output = run_task_to_completion(&foreground_executor, task);
MeasuredTaskOutput {
- frame_trace_scope: measured_input.frame_trace_scope.take(),
+ trace_scope: measured_input.trace_scope.take(),
report: report.clone(),
_output: output,
}
@@ -549,8 +556,8 @@ impl<'a, 'measurement> BenchAppContext<'a, 'measurement> {
/// windows. The entity should be part of the window's render tree, such as the
/// root view or a child of it.
///
- /// Frame timings are collected through the GPUI frame profiler
- /// ([`crate::profiler::record_frame_timing`]), which is enabled for the
+ /// Frame events are collected through the GPUI frame profiler
+ /// ([`crate::profiler::record_frame_event`]), which is enabled for the
/// duration of the measurement.
pub fn bench_renderer<V>(
&mut self,
@@ -567,7 +574,7 @@ impl<'a, 'measurement> BenchAppContext<'a, 'measurement> {
.expect("cannot benchmark renderer for entity without a current window");
let dispatcher = self.background_executor.dispatcher().clone();
- let collector = FrameTraceScope::start();
+ let collector = TraceScope::start();
let mut benchmark = || {
// Work already queued at frame start delays the frame in
@@ -590,12 +597,12 @@ impl<'a, 'measurement> BenchAppContext<'a, 'measurement> {
};
bencher.iter(&mut benchmark);
- let timings = collector.finish();
- self.report.record_frame_timings(
- timings
- .iter()
- .filter(|timing| timing.window_id == window_id),
- );
+ let events = collector.finish();
+ self.report
+ .record_frame_timings(events.iter().filter(|event| match event {
+ FrameEvent::Draw(timing) => timing.window_id == window_id,
+ FrameEvent::Present(timing) => timing.window_id == window_id,
+ }));
self.replace_bencher(bencher);
}
diff --git a/crates/gpui/src/profiler.rs b/crates/gpui/src/profiler.rs
index e66a0025cf2..e850901330e 100644
--- a/crates/gpui/src/profiler.rs
+++ b/crates/gpui/src/profiler.rs
@@ -1,12 +1,16 @@
+#[cfg(feature = "profiler")]
+use hdrhistogram::Histogram;
use itertools::Itertools;
use scheduler::{Instant, SpawnTime};
+#[cfg(feature = "profiler")]
+use smallvec::SmallVec;
use std::{
cell::LazyCell,
collections::{HashMap, VecDeque},
hash::{DefaultHasher, Hash, Hasher},
sync::{
Arc,
- atomic::{AtomicBool, Ordering},
+ atomic::{AtomicU64, Ordering},
},
thread::ThreadId,
time::Duration,
@@ -14,11 +18,12 @@ use std::{
mod actions;
pub use actions::{ActionStatistics, ActionTiming, take_action_stats};
-pub(crate) use actions::{save_action_timing, update_running_action};
use serde::{Deserialize, Serialize};
-use crate::{SharedString, TasksIncluded, WindowId};
+#[cfg(feature = "profiler")]
+use crate::{Action, App, WindowId};
+use crate::{SharedString, TasksIncluded};
#[cfg(feature = "profiler")]
#[doc(hidden)]
@@ -675,42 +680,103 @@ pub fn get_current_thread_task_timings(include_running: TasksIncluded) -> Thread
THREAD_TIMINGS.with(|timings| timings.lock().get_thread_task_timings(include_running))
}
-static PROFILER_ENABLED: AtomicBool = AtomicBool::new(false);
+const TRACE_SETTING_ENABLED: u64 = 1 << 63;
+const TRACE_SCOPE_COUNT_MASK: u64 = TRACE_SETTING_ENABLED - 1;
+static TRACE_STATE: AtomicU64 = AtomicU64::new(0);
-/// Enables or disables task timing trace collection at runtime.
+/// Enables or disables profiler trace collection at runtime.
///
-/// When transitioning from enabled to disabled, `add_task_timing` becomes a
+/// When transitioning from enabled to disabled, `add_task_timing` becomes
/// cheaper since only cheap statistics are gathered. The existing per-thread
-/// buffers for traces are cleared so stale data isn't reported after a later
-/// re-enable. Calls with the current value are a no-op.
+/// task buffers and the frame-event buffer are cleared so stale data isn't
+/// reported after a later re-enable. Active trace scopes keep collection enabled
+/// until the last scope ends. Calls with the current setting are a no-op.
pub fn set_trace_enabled(enabled: bool) -> bool {
- if PROFILER_ENABLED.swap(enabled, Ordering::AcqRel) == enabled {
- return false;
+ let mut state = TRACE_STATE.load(Ordering::Acquire);
+ loop {
+ let was_enabled = state & TRACE_SETTING_ENABLED != 0;
+ if was_enabled == enabled {
+ return false;
+ }
+
+ let next_state = if enabled {
+ state | TRACE_SETTING_ENABLED
+ } else {
+ state & TRACE_SCOPE_COUNT_MASK
+ };
+ match TRACE_STATE.compare_exchange_weak(
+ state,
+ next_state,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ if next_state == 0 {
+ clear_trace_buffers();
+ }
+ return true;
+ }
+ Err(updated_state) => state = updated_state,
+ }
}
+}
+
+#[cfg(any(feature = "bench", all(test, feature = "profiler")))]
+pub(crate) struct TraceGuard;
+
+#[cfg(any(feature = "bench", all(test, feature = "profiler")))]
+pub(crate) fn trace_scope() -> TraceGuard {
+ let incremented = TRACE_STATE.fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| {
+ (state & TRACE_SCOPE_COUNT_MASK < TRACE_SCOPE_COUNT_MASK).then_some(state + 1)
+ });
+ assert!(incremented.is_ok(), "too many active profiler trace scopes");
+ TraceGuard
+}
- if !enabled {
- for (_, timings) in upgraded_thread_timings() {
- let mut timings = timings.lock();
- timings.timings.clear();
- timings.timings.shrink_to_fit();
- timings.total_pushed = 0;
+#[cfg(any(feature = "bench", all(test, feature = "profiler")))]
+impl Drop for TraceGuard {
+ fn drop(&mut self) {
+ let previous_state =
+ TRACE_STATE.fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| {
+ (state & TRACE_SCOPE_COUNT_MASK > 0).then_some(state - 1)
+ });
+ match previous_state {
+ Ok(1) => clear_trace_buffers(),
+ Ok(_) => {}
+ Err(_) => debug_assert!(false, "profiler trace scope count underflowed"),
}
}
- true
}
-/// Returns whether task timing tracing is enabled.
+/// Returns whether profiler trace collection is enabled.
pub fn trace_enabled() -> bool {
- PROFILER_ENABLED.load(Ordering::Relaxed)
+ TRACE_STATE.load(Ordering::Relaxed) != 0
+}
+
+fn clear_trace_buffers() {
+ for (_, timings) in upgraded_thread_timings() {
+ let mut timings = timings.lock();
+ timings.timings.clear();
+ timings.timings.shrink_to_fit();
+ timings.total_pushed = 0;
+ }
+ #[cfg(feature = "profiler")]
+ {
+ let mut frames = FRAME_TIMINGS.lock();
+ frames.timings.clear();
+ frames.timings.shrink_to_fit();
+ frames.total_pushed = 0;
+ }
}
/// Timing for a single drawn window frame.
+#[cfg(feature = "profiler")]
#[derive(Debug, Copy, Clone)]
pub struct FrameTiming {
/// The window that was drawn.
pub window_id: WindowId,
/// When the frame first became dirty (its first invalidation). `None` if
- /// frame tracing was not yet enabled when the invalidation occurred.
+ /// profiler tracing was not yet enabled when the invalidation occurred.
pub dirty_at: Option<Instant>,
/// Number of invalidations coalesced into this frame.
pub invalidations: u64,
@@ -720,6 +786,7 @@ pub struct FrameTiming {
pub draw_end: Instant,
}
+#[cfg(feature = "profiler")]
impl FrameTiming {
/// Time spent inside `Window::draw`.
pub fn draw_duration(&self) -> Duration {
@@ -734,50 +801,278 @@ impl FrameTiming {
}
}
-// Allow 16MiB of frame timing entries.
-const MAX_FRAME_TIMINGS: usize = (16 * 1024 * 1024) / core::mem::size_of::<FrameTiming>();
+/// A newly drawn frame reaching the screen.
+#[cfg(feature = "profiler")]
+#[derive(Debug, Copy, Clone)]
+pub struct PresentTiming {
+ /// The window whose frame was presented.
+ pub window_id: WindowId,
+ /// When the frame was presented.
+ pub presented_at: Instant,
+ /// The interval since the previous newly drawn frame was presented, when
+ /// both frames belong to an active animation.
+ pub animation_interval: Option<Duration>,
+}
-struct FrameTimings {
- timings: VecDeque<FrameTiming>,
- total_pushed: u64,
+/// A frame event observed by the profiler.
+#[cfg(feature = "profiler")]
+#[derive(Debug, Copy, Clone)]
+pub enum FrameEvent {
+ /// A window frame was drawn.
+ Draw(FrameTiming),
+ /// A newly drawn window frame was presented.
+ Present(PresentTiming),
}
-static FRAME_TIMINGS: spin::Mutex<FrameTimings> = spin::Mutex::new(FrameTimings {
- timings: VecDeque::new(),
- total_pushed: 0,
-});
+/// A point-in-time snapshot of the frame-duration histograms for a window,
+/// suitable for external formatting.
+#[cfg(feature = "profiler")]
+#[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>,
+}
+
+/// A point-in-time snapshot of the input-latency histograms for a window,
+/// suitable for external formatting.
+#[cfg(feature = "profiler")]
+#[derive(Clone)]
+pub struct InputLatencySnapshot {
+ /// Histogram of input-to-frame latency samples, in nanoseconds.
+ pub latency_histogram: Histogram<u64>,
+ /// Histogram of input events coalesced per rendered frame.
+ pub events_per_frame_histogram: Histogram<u64>,
+ /// Count of input events that arrived mid-draw and were excluded from
+ /// latency recording.
+ pub mid_draw_events_dropped: u64,
+}
-static FRAME_TRACE_ENABLED: AtomicBool = AtomicBool::new(false);
+#[cfg(feature = "profiler")]
+enum WindowActivity {
+ Input { started_at: Instant },
+ Draw { started_at: Instant },
+}
-/// Enables or disables frame timing collection at runtime.
+/// Collects profiling information for one window.
///
-/// When transitioning from enabled to disabled, the buffered frame timings are
-/// cleared so stale data isn't reported after a later re-enable. Returns false
-/// if the value was unchanged.
-pub fn set_frame_trace_enabled(enabled: bool) -> bool {
- if FRAME_TRACE_ENABLED.swap(enabled, Ordering::AcqRel) == enabled {
- return false;
+/// Aggregate histograms are always populated when the `profiler` feature is
+/// compiled in. Individual draw and present events are added to the global
+/// profiler buffer only while tracing is enabled.
+#[cfg(feature = "profiler")]
+pub struct WindowProfiler {
+ window_id: WindowId,
+ active_activities: SmallVec<[WindowActivity; 4]>,
+ draw_duration_histogram: Histogram<u64>,
+ present_interval_histogram: Histogram<u64>,
+ first_input_at: Option<Instant>,
+ pending_input_count: u64,
+ input_latency_histogram: Histogram<u64>,
+ events_per_frame_histogram: Histogram<u64>,
+ mid_draw_events_dropped: u64,
+ last_present_at: Option<Instant>,
+ animating_at_last_present: bool,
+ drew_since_last_present: bool,
+}
+
+#[cfg(feature = "profiler")]
+impl WindowProfiler {
+ /// Creates a profiler for a window.
+ pub fn new(window_id: WindowId) -> anyhow::Result<Self> {
+ Ok(Self {
+ window_id,
+ active_activities: SmallVec::new(),
+ draw_duration_histogram: Histogram::new(3).map_err(|error| {
+ anyhow::anyhow!("Failed to create draw duration histogram: {error}")
+ })?,
+ present_interval_histogram: Histogram::new(3).map_err(|error| {
+ anyhow::anyhow!("Failed to create present interval histogram: {error}")
+ })?,
+ first_input_at: None,
+ pending_input_count: 0,
+ input_latency_histogram: Histogram::new(3).map_err(|error| {
+ anyhow::anyhow!("Failed to create input latency histogram: {error}")
+ })?,
+ events_per_frame_histogram: Histogram::new(3).map_err(|error| {
+ anyhow::anyhow!("Failed to create events per frame histogram: {error}")
+ })?,
+ mid_draw_events_dropped: 0,
+ last_present_at: None,
+ animating_at_last_present: false,
+ drew_since_last_present: false,
+ })
}
- if !enabled {
- let mut frames = FRAME_TIMINGS.lock();
- frames.timings.clear();
- frames.timings.shrink_to_fit();
- frames.total_pushed = 0;
+ /// Records the beginning of an input dispatch.
+ pub fn begin_input(&mut self) {
+ self.active_activities.push(WindowActivity::Input {
+ started_at: Instant::now(),
+ });
+ }
+
+ /// Records the end of an input dispatch.
+ pub fn end_input(&mut self, caused_invalidation: bool) {
+ let Some(WindowActivity::Input { started_at }) = self.active_activities.pop() else {
+ debug_assert!(false, "input activity must be the current window activity");
+ return;
+ };
+
+ if !caused_invalidation {
+ return;
+ }
+
+ let arrived_during_draw = self
+ .active_activities
+ .iter()
+ .any(|activity| matches!(activity, WindowActivity::Draw { .. }));
+ if arrived_during_draw {
+ self.mid_draw_events_dropped += 1;
+ } else {
+ self.first_input_at.get_or_insert(started_at);
+ self.pending_input_count += 1;
+ }
+ }
+
+ /// Records the beginning of an action handler.
+ pub fn begin_action_handler(&mut self, action: &(dyn Action + 'static), cx: &mut App) {
+ actions::update_running_action(action, cx);
+ }
+
+ /// Records the end of the current action handler.
+ pub fn end_action_handler(&mut self) {
+ actions::save_action_timing();
+ }
+
+ /// Records the beginning of a window draw.
+ pub fn begin_draw(&mut self) {
+ self.active_activities.push(WindowActivity::Draw {
+ started_at: Instant::now(),
+ });
+ }
+
+ /// Records the end of a window draw.
+ pub fn end_draw(&mut self, dirty_at: Option<Instant>, invalidations: u64) {
+ let Some(WindowActivity::Draw {
+ started_at: draw_start,
+ }) = self.active_activities.pop()
+ else {
+ debug_assert!(false, "draw activity must be the current window activity");
+ return;
+ };
+
+ self.drew_since_last_present = true;
+ let draw_end = Instant::now();
+ self.record_draw_duration(draw_end.duration_since(draw_start));
+ record_frame_event(FrameEvent::Draw(FrameTiming {
+ window_id: self.window_id,
+ dirty_at,
+ invalidations,
+ draw_start,
+ draw_end,
+ }));
+ }
+
+ /// Records that a frame was presented.
+ ///
+ /// `next_frame_scheduled` marks the animation state for the interval ending
+ /// at the next newly drawn frame's presentation.
+ pub fn record_present(&mut self, window_active: bool, next_frame_scheduled: bool) {
+ self.record_present_at(Instant::now(), window_active, next_frame_scheduled);
+ }
+
+ /// Returns a snapshot of the current input-latency histograms.
+ pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
+ InputLatencySnapshot {
+ latency_histogram: self.input_latency_histogram.clone(),
+ events_per_frame_histogram: self.events_per_frame_histogram.clone(),
+ mid_draw_events_dropped: self.mid_draw_events_dropped,
+ }
+ }
+
+ /// Returns a snapshot of the current frame-duration histograms.
+ pub fn frame_duration_snapshot(&self) -> FrameDurationSnapshot {
+ FrameDurationSnapshot {
+ draw_duration_histogram: self.draw_duration_histogram.clone(),
+ present_interval_histogram: self.present_interval_histogram.clone(),
+ }
+ }
+
+ fn record_present_at(
+ &mut self,
+ presented_at: Instant,
+ window_active: bool,
+ next_frame_scheduled: bool,
+ ) {
+ if let Some(first_input_at) = self.first_input_at.take() {
+ let latency_nanos = presented_at.duration_since(first_input_at).as_nanos() as u64;
+ self.input_latency_histogram.record(latency_nanos).ok();
+ }
+ if self.pending_input_count > 0 {
+ self.events_per_frame_histogram
+ .record(self.pending_input_count)
+ .ok();
+ self.pending_input_count = 0;
+ }
+
+ if !std::mem::take(&mut self.drew_since_last_present) {
+ return;
+ }
+
+ let animation_interval = if self.animating_at_last_present && window_active {
+ self.last_present_at
+ .map(|last_present_at| presented_at.duration_since(last_present_at))
+ } else {
+ None
+ };
+
+ if let Some(animation_interval) = animation_interval {
+ self.present_interval_histogram
+ .record(animation_interval.as_nanos() as u64)
+ .ok();
+ }
+
+ record_frame_event(FrameEvent::Present(PresentTiming {
+ window_id: self.window_id,
+ presented_at,
+ animation_interval,
+ }));
+
+ self.last_present_at = Some(presented_at);
+ self.animating_at_last_present = next_frame_scheduled && window_active;
+ }
+
+ fn record_draw_duration(&mut self, duration: Duration) {
+ self.draw_duration_histogram
+ .record(duration.as_nanos() as u64)
+ .ok();
+ self.drew_since_last_present = true;
}
- true
}
-/// Returns whether frame timing collection is enabled.
-pub fn frame_trace_enabled() -> bool {
- FRAME_TRACE_ENABLED.load(Ordering::Relaxed)
+// Allow 16MiB of frame event entries.
+#[cfg(feature = "profiler")]
+const MAX_FRAME_TIMINGS: usize = (16 * 1024 * 1024) / core::mem::size_of::<FrameEvent>();
+
+#[cfg(feature = "profiler")]
+struct FrameTimings {
+ timings: VecDeque<FrameEvent>,
+ total_pushed: u64,
}
-/// Records the timing of a drawn window frame.
+#[cfg(feature = "profiler")]
+static FRAME_TIMINGS: spin::Mutex<FrameTimings> = spin::Mutex::new(FrameTimings {
+ timings: VecDeque::new(),
+ total_pushed: 0,
+});
+
+/// Records a frame event.
///
-/// No-op unless frame tracing is enabled via [`set_frame_trace_enabled`].
-pub fn record_frame_timing(timing: FrameTiming) {
- if !frame_trace_enabled() {
+/// No-op unless profiler tracing is enabled via [`set_trace_enabled`].
+#[cfg(feature = "profiler")]
+pub fn record_frame_event(event: FrameEvent) {
+ if !trace_enabled() {
return;
}
std::hint::cold_path(); // optimize for when profiling is off
@@ -786,34 +1081,37 @@ pub fn record_frame_timing(timing: FrameTiming) {
if frames.timings.len() >= MAX_FRAME_TIMINGS {
frames.timings.pop_front();
}
- frames.timings.push_back(timing);
+ frames.timings.push_back(event);
frames.total_pushed += 1;
}
-/// Drains frame timings recorded after this collector was created, tracking a
+/// Drains frame events recorded after this collector was created, tracking a
/// cursor so each call to [`Self::collect_unseen`] returns only new entries.
+#[cfg(feature = "profiler")]
pub struct FrameTimingCollector {
cursor: u64,
}
+#[cfg(feature = "profiler")]
impl Default for FrameTimingCollector {
fn default() -> Self {
Self::new()
}
}
+#[cfg(feature = "profiler")]
impl FrameTimingCollector {
- /// Creates a collector that only sees frames recorded from this point on.
+ /// Creates a collector that only sees frame events recorded from this point on.
pub fn new() -> Self {
Self {
cursor: FRAME_TIMINGS.lock().total_pushed,
}
}
- /// Returns frame timings recorded since the previous call (or since the
+ /// Returns frame events recorded since the previous call (or since the
/// collector was created). If the ring buffer wrapped around since the
/// previous poll, the evicted entries are lost.
- pub fn collect_unseen(&mut self) -> Vec<FrameTiming> {
+ pub fn collect_unseen(&mut self) -> Vec<FrameEvent> {
let frames = FRAME_TIMINGS.lock();
let buffer_len = frames.timings.len() as u64;
let buffer_start = frames.total_pushed.saturating_sub(buffer_len);
@@ -828,3 +1126,309 @@ impl FrameTimingCollector {
unseen
}
}
+
+#[cfg(all(test, feature = "profiler"))]
+mod tests {
+ use super::*;
+ use std::sync::{Mutex, MutexGuard};
+
+ #[test]
+ fn records_draw_events_only_while_tracing() {
+ let _trace_test_guard = TraceTestGuard::new();
+ let window_id = WindowId::from(0xD0A0);
+ let mut window_profiler =
+ WindowProfiler::new(window_id).expect("window profiler should initialize");
+ let dirty_at = Instant::now();
+ let mut collector = FrameTimingCollector::new();
+
+ window_profiler.begin_draw();
+ window_profiler.end_draw(Some(dirty_at), 3);
+ assert!(
+ collector
+ .collect_unseen()
+ .iter()
+ .all(|event| !event_matches_window(*event, window_id))
+ );
+
+ set_trace_enabled(true);
+ let mut collector = FrameTimingCollector::new();
+ window_profiler.begin_draw();
+ window_profiler.end_draw(Some(dirty_at), 3);
+
+ let timing = collector
+ .collect_unseen()
+ .into_iter()
+ .find_map(|event| match event {
+ FrameEvent::Draw(timing) if timing.window_id == window_id => Some(timing),
+ _ => None,
+ })
+ .expect("draw event should be recorded while tracing");
+ assert_eq!(timing.dirty_at, Some(dirty_at));
+ assert_eq!(timing.invalidations, 3);
+ assert!(timing.draw_start >= dirty_at);
+ }
+
+ #[test]
+ fn records_present_events_for_newly_drawn_frames() {
+ let _trace_test_guard = TraceTestGuard::new();
+ set_trace_enabled(true);
+ let window_id = WindowId::from(0xA11E);
+ let mut window_profiler =
+ WindowProfiler::new(window_id).expect("window profiler should initialize");
+ let start = Instant::now();
+ let mut collector = FrameTimingCollector::new();
+
+ window_profiler.record_draw_duration(Duration::from_millis(2));
+ window_profiler.record_present_at(start, true, true);
+ window_profiler.record_draw_duration(Duration::from_millis(2));
+ window_profiler.record_present_at(start + FRAME, true, true);
+ window_profiler.record_present_at(start + FRAME + FRAME / 2, true, true);
+
+ let present_timings = collector
+ .collect_unseen()
+ .into_iter()
+ .filter_map(|event| match event {
+ FrameEvent::Present(timing) if timing.window_id == window_id => Some(timing),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ let [first_present, second_present] = present_timings.as_slice() else {
+ panic!("expected exactly two present events, got {present_timings:?}");
+ };
+ assert_eq!(first_present.animation_interval, None);
+ assert_eq!(second_present.animation_interval, Some(FRAME));
+
+ #[cfg(feature = "profiler")]
+ {
+ assert_eq!(window_profiler.present_interval_histogram.len(), 1);
+ assert!(
+ window_profiler.present_interval_histogram.max()
+ >= second_present
+ .animation_interval
+ .expect("second present should have an animation interval")
+ .as_nanos() as u64
+ );
+ }
+ }
+
+ #[test]
+ fn disabling_tracing_clears_frame_events() {
+ let _trace_test_guard = TraceTestGuard::new();
+ set_trace_enabled(true);
+ let window_id = WindowId::from(0xC1EA);
+ let mut window_profiler =
+ WindowProfiler::new(window_id).expect("window profiler should initialize");
+ let mut collector = FrameTimingCollector::new();
+
+ window_profiler.begin_draw();
+ window_profiler.end_draw(None, 0);
+ assert!(
+ FRAME_TIMINGS
+ .lock()
+ .timings
+ .iter()
+ .copied()
+ .any(|event| event_matches_window(event, window_id))
+ );
+
+ set_trace_enabled(false);
+ assert!(
+ collector
+ .collect_unseen()
+ .iter()
+ .all(|event| !event_matches_window(*event, window_id))
+ );
+ }
+
+ #[cfg(feature = "profiler")]
+ #[test]
+ fn records_intervals_only_between_animation_frames() {
+ let mut window_profiler =
+ WindowProfiler::new(WindowId::from(1)).expect("window profiler should initialize");
+ let start = Instant::now();
+
+ draw_and_present(&mut window_profiler, start, true, true);
+ assert_eq!(window_profiler.present_interval_histogram.len(), 0);
+
+ draw_and_present(&mut window_profiler, start + FRAME, true, true);
+ assert_eq!(window_profiler.present_interval_histogram.len(), 1);
+
+ draw_and_present(&mut window_profiler, start + FRAME * 2, true, false);
+ assert_eq!(window_profiler.present_interval_histogram.len(), 2);
+
+ draw_and_present(&mut window_profiler, start + FRAME * 100, true, true);
+ assert_eq!(window_profiler.present_interval_histogram.len(), 2);
+ }
+
+ #[cfg(feature = "profiler")]
+ #[test]
+ fn missed_frames_stretch_the_recorded_interval() {
+ let mut window_profiler =
+ WindowProfiler::new(WindowId::from(2)).expect("window profiler should initialize");
+ let start = Instant::now();
+
+ draw_and_present(&mut window_profiler, start, true, true);
+ draw_and_present(&mut window_profiler, start + FRAME * 5, true, true);
+
+ let recorded = window_profiler.present_interval_histogram.max();
+ assert!(recorded >= (FRAME * 4).as_nanos() as u64);
+ }
+
+ #[cfg(feature = "profiler")]
+ #[test]
+ fn ignores_re_presents_of_unchanged_frames() {
+ let mut window_profiler =
+ WindowProfiler::new(WindowId::from(3)).expect("window profiler should initialize");
+ let start = Instant::now();
+
+ draw_and_present(&mut window_profiler, start, true, true);
+ window_profiler.record_present_at(start + FRAME / 2, true, true);
+ draw_and_present(&mut window_profiler, start + FRAME, true, true);
+
+ assert_eq!(window_profiler.present_interval_histogram.len(), 1);
+ assert!(
+ window_profiler.present_interval_histogram.max() >= (FRAME * 3 / 4).as_nanos() as u64
+ );
+ }
+
+ #[cfg(feature = "profiler")]
+ #[test]
+ fn skips_intervals_for_inactive_windows() {
+ let mut window_profiler =
+ WindowProfiler::new(WindowId::from(4)).expect("window profiler should initialize");
+ let start = Instant::now();
+
+ draw_and_present(&mut window_profiler, start, false, true);
+ draw_and_present(&mut window_profiler, start + FRAME, false, true);
+ assert_eq!(window_profiler.present_interval_histogram.len(), 0);
+
+ draw_and_present(&mut window_profiler, start + FRAME * 2, true, true);
+ assert_eq!(window_profiler.present_interval_histogram.len(), 0);
+
+ draw_and_present(&mut window_profiler, start + FRAME * 3, true, true);
+ assert_eq!(window_profiler.present_interval_histogram.len(), 1);
+ }
+
+ #[cfg(feature = "profiler")]
+ #[test]
+ fn records_every_draw_duration() {
+ let mut window_profiler =
+ WindowProfiler::new(WindowId::from(5)).expect("window profiler should initialize");
+
+ window_profiler.record_draw_duration(Duration::from_millis(2));
+ window_profiler.record_draw_duration(Duration::from_millis(40));
+
+ let snapshot = window_profiler.frame_duration_snapshot();
+ assert_eq!(snapshot.draw_duration_histogram.len(), 2);
+ assert!(snapshot.draw_duration_histogram.max() >= 39_000_000);
+ }
+
+ #[test]
+ fn records_input_latency_at_the_frame_presentation_timestamp() {
+ let mut window_profiler =
+ WindowProfiler::new(WindowId::from(6)).expect("window profiler should initialize");
+ let first_input_at = Instant::now();
+ let presented_at = first_input_at + Duration::from_millis(12);
+
+ begin_input_at(&mut window_profiler, first_input_at);
+ window_profiler.end_input(true);
+ begin_input_at(
+ &mut window_profiler,
+ first_input_at + Duration::from_millis(2),
+ );
+ window_profiler.end_input(true);
+ window_profiler.record_draw_duration(Duration::from_millis(2));
+ window_profiler.record_present_at(presented_at, true, false);
+
+ let snapshot = window_profiler.input_latency_snapshot();
+ assert_eq!(snapshot.latency_histogram.len(), 1);
+ assert!(snapshot.latency_histogram.max() >= Duration::from_millis(12).as_nanos() as u64);
+ assert_eq!(snapshot.events_per_frame_histogram.len(), 1);
+ assert_eq!(snapshot.events_per_frame_histogram.max(), 2);
+ assert_eq!(snapshot.mid_draw_events_dropped, 0);
+ }
+
+ #[test]
+ fn excludes_input_that_arrives_during_a_draw() {
+ let mut window_profiler =
+ WindowProfiler::new(WindowId::from(7)).expect("window profiler should initialize");
+
+ window_profiler.begin_draw();
+ begin_input_at(&mut window_profiler, Instant::now());
+ window_profiler.end_input(true);
+ window_profiler.end_draw(None, 0);
+
+ let snapshot = window_profiler.input_latency_snapshot();
+ assert!(snapshot.latency_histogram.is_empty());
+ assert!(snapshot.events_per_frame_histogram.is_empty());
+ assert_eq!(snapshot.mid_draw_events_dropped, 1);
+ }
+
+ #[test]
+ fn overlapping_trace_scopes_keep_tracing_enabled() {
+ let _trace_test_guard = TraceTestGuard::new();
+ let first_scope = trace_scope();
+ let second_scope = trace_scope();
+
+ assert!(trace_enabled());
+ drop(first_scope);
+ assert!(trace_enabled());
+ drop(second_scope);
+ assert!(!trace_enabled());
+ }
+
+ const FRAME: Duration = Duration::from_millis(16);
+ static TRACE_TEST_LOCK: Mutex<()> = Mutex::new(());
+
+ struct TraceTestGuard {
+ was_enabled: bool,
+ _lock: MutexGuard<'static, ()>,
+ }
+
+ impl TraceTestGuard {
+ fn new() -> Self {
+ let lock = TRACE_TEST_LOCK
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let was_enabled = trace_enabled();
+ set_trace_enabled(false);
+ Self {
+ was_enabled,
+ _lock: lock,
+ }
+ }
+ }
+
+ impl Drop for TraceTestGuard {
+ fn drop(&mut self) {
+ set_trace_enabled(false);
+ if self.was_enabled {
+ set_trace_enabled(true);
+ }
+ }
+ }
+
+ fn event_matches_window(event: FrameEvent, window_id: WindowId) -> bool {
+ match event {
+ FrameEvent::Draw(timing) => timing.window_id == window_id,
+ FrameEvent::Present(timing) => timing.window_id == window_id,
+ }
+ }
+
+ fn begin_input_at(window_profiler: &mut WindowProfiler, started_at: Instant) {
+ window_profiler
+ .active_activities
+ .push(WindowActivity::Input { started_at });
+ }
+
+ #[cfg(feature = "profiler")]
+ fn draw_and_present(
+ window_profiler: &mut WindowProfiler,
+ presented_at: Instant,
+ window_active: bool,
+ next_frame_scheduled: bool,
+ ) {
+ window_profiler.record_draw_duration(Duration::from_millis(2));
+ window_profiler.record_present_at(presented_at, window_active, next_frame_scheduled);
+ }
+}
diff --git a/crates/gpui/src/profiler/actions.rs b/crates/gpui/src/profiler/actions.rs
index dcb68dfe15d..efa9b756db6 100644
--- a/crates/gpui/src/profiler/actions.rs
+++ b/crates/gpui/src/profiler/actions.rs
@@ -2,6 +2,7 @@ use std::time::{Duration, Instant};
use itertools::Itertools;
+#[cfg(feature = "profiler")]
use crate::action::Action;
#[doc(hidden)]
@@ -190,20 +191,12 @@ pub(crate) fn update_running_action(action: &(dyn Action + 'static), cx: &mut cr
ACTION_STATISTICS.lock().update_running_action(action, now);
}
-#[doc(hidden)]
-#[cfg(not(feature = "profiler"))]
-pub(crate) fn update_running_action(_: &(dyn Action + 'static), _: &mut crate::App) {}
-
#[doc(hidden)]
#[cfg(feature = "profiler")]
pub(crate) fn save_action_timing() {
ACTION_STATISTICS.lock().save_action_timing();
}
-#[doc(hidden)]
-#[cfg(not(feature = "profiler"))]
-pub(crate) fn save_action_timing() {}
-
#[doc(hidden)]
#[cfg(feature = "profiler")]
pub fn take_action_stats() -> ActionStatistics {
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index bb0412a0777..3bb89308eb4 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -1,5 +1,7 @@
#[cfg(any(feature = "inspector", debug_assertions))]
use crate::Inspector;
+#[cfg(feature = "profiler")]
+use crate::profiler;
use crate::{
Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,
@@ -17,7 +19,7 @@ use crate::{
SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextRenderingMode, TextStyle,
TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
- WindowOptions, WindowParams, WindowTextSystem, point, prelude::*, profiler, px, rems, size,
+ WindowOptions, WindowParams, WindowTextSystem, point, prelude::*, px, rems, size,
transparent_black,
};
@@ -30,11 +32,6 @@ use futures::FutureExt;
use futures::channel::oneshot;
use gpui_util::post_inc;
use gpui_util::{ResultExt, measure};
-#[cfg(any(
- feature = "input-latency-histogram",
- feature = "frame-duration-histogram"
-))]
-use hdrhistogram::Histogram;
use itertools::FoldWhile::{Continue, Done};
use itertools::Itertools;
use parking_lot::RwLock;
@@ -122,14 +119,16 @@ struct WindowInvalidatorInner {
pub draw_phase: DrawPhase,
pub dirty_views: FxHashSet<EntityId>,
pub update_count: usize,
+ #[cfg(feature = "profiler")]
pub frame_dirty: FrameDirtyAccumulator,
pub platform_waker: Option<Rc<dyn Fn()>>,
}
/// Per-frame invalidation bookkeeping, drained at draw time and emitted to the
/// frame profiler. Tracks when the current frame first became dirty and how
-/// many invalidations were coalesced into it. Only populated while
-/// `profiler::frame_trace_enabled()` is set.
+/// many invalidations were coalesced into it. Only populated when the profiler
+/// is compiled in and `profiler::trace_enabled()` is set.
+#[cfg(feature = "profiler")]
#[derive(Default)]
struct FrameDirtyAccumulator {
dirty_at: Option<Instant>,
@@ -149,6 +148,7 @@ impl WindowInvalidator {
draw_phase: DrawPhase::None,
dirty_views: FxHashSet::default(),
update_count: 0,
+ #[cfg(feature = "profiler")]
frame_dirty: FrameDirtyAccumulator::default(),
platform_waker: None,
})),
@@ -160,6 +160,7 @@ impl WindowInvalidator {
inner.update_count += 1;
inner.dirty_views.insert(entity);
if inner.draw_phase == DrawPhase::None {
+ #[cfg(feature = "profiler")]
Self::record_frame_dirty(&mut inner);
let became_dirty = !inner.dirty;
inner.dirty = true;
@@ -185,6 +186,7 @@ impl WindowInvalidator {
inner.dirty = dirty;
if dirty {
inner.update_count += 1;
+ #[cfg(feature = "profiler")]
Self::record_frame_dirty(&mut inner);
}
let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
@@ -222,13 +224,15 @@ impl WindowInvalidator {
self.inner.borrow().update_count
}
+ #[cfg(feature = "profiler")]
fn record_frame_dirty(inner: &mut WindowInvalidatorInner) {
- if profiler::frame_trace_enabled() {
+ if profiler::trace_enabled() {
inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
inner.frame_dirty.invalidations += 1;
}
}
+ #[cfg(feature = "profiler")]
fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
mem::take(&mut self.inner.borrow_mut().frame_dirty)
}
@@ -1160,10 +1164,8 @@ pub struct Window {
/// Tracks recent input event timestamps to determine if input is arriving at a high rate.
/// Used to selectively enable VRR optimization only when input rate exceeds 60fps.
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,
+ #[cfg(feature = "profiler")]
+ window_profiler: profiler::WindowProfiler,
last_input_modality: InputModality,
pub(crate) refreshing: bool,
pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
@@ -1236,182 +1238,6 @@ impl InputRateTracker {
}
}
-/// A point-in-time snapshot of the input-latency histograms for a window,
-/// suitable for external formatting.
-#[cfg(feature = "input-latency-histogram")]
-#[derive(Clone)]
-pub struct InputLatencySnapshot {
- /// Histogram of input-to-frame latency samples, in nanoseconds.
- pub latency_histogram: Histogram<u64>,
- /// Histogram of input events coalesced per rendered frame.
- pub events_per_frame_histogram: Histogram<u64>,
- /// Count of input events that arrived mid-draw and were excluded from
- /// latency recording.
- pub mid_draw_events_dropped: u64,
-}
-
-/// Records the time between when the first input event in a frame is dispatched
-/// and when the resulting frame is presented, capturing worst-case latency when
-/// multiple events are coalesced into a single frame.
-#[cfg(feature = "input-latency-histogram")]
-struct InputLatencyTracker {
- /// Timestamp of the first unrendered input event in the current frame;
- /// cleared when a frame is presented.
- first_input_at: Option<Instant>,
- /// Count of input events received since the last frame was presented.
- pending_input_count: u64,
- /// Histogram of input-to-frame latency samples, in nanoseconds.
- latency_histogram: Histogram<u64>,
- /// Histogram of input events coalesced per rendered frame.
- events_per_frame_histogram: Histogram<u64>,
- /// Count of input events that arrived mid-draw and were excluded from
- /// latency recording because their effects won't appear until the next frame.
- mid_draw_events_dropped: u64,
-}
-
-#[cfg(feature = "input-latency-histogram")]
-impl InputLatencyTracker {
- fn new() -> Result<Self> {
- Ok(Self {
- first_input_at: None,
- pending_input_count: 0,
- latency_histogram: Histogram::new(3)
- .map_err(|e| anyhow!("Failed to create input latency histogram: {e}"))?,
- events_per_frame_histogram: Histogram::new(3)
- .map_err(|e| anyhow!("Failed to create events per frame histogram: {e}"))?,
- mid_draw_events_dropped: 0,
- })
- }
-
- /// Record that an input event was dispatched at the given time.
- /// Only the first event's timestamp per frame is retained (worst-case latency).
- fn record_input(&mut self, dispatch_time: Instant) {
- self.first_input_at.get_or_insert(dispatch_time);
- self.pending_input_count += 1;
- }
-
- /// Record that an input event arrived during a draw phase and was excluded
- /// from latency tracking.
- fn record_mid_draw_input(&mut self) {
- self.mid_draw_events_dropped += 1;
- }
-
- /// Record that a frame was presented, flushing pending latency and coalescing samples.
- fn record_frame_presented(&mut self) {
- if let Some(first_input_at) = self.first_input_at.take() {
- let latency_nanos = first_input_at.elapsed().as_nanos() as u64;
- self.latency_histogram.record(latency_nanos).ok();
- }
- if self.pending_input_count > 0 {
- self.events_per_frame_histogram
- .record(self.pending_input_count)
- .ok();
- self.pending_input_count = 0;
- }
- }
-
- fn snapshot(&self) -> InputLatencySnapshot {
- InputLatencySnapshot {
- latency_histogram: self.latency_histogram.clone(),
- events_per_frame_histogram: self.events_per_frame_histogram.clone(),
- mid_draw_events_dropped: self.mid_draw_events_dropped,
- }
- }
-}
-
-/// 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,
@@ -2018,10 +1844,8 @@ impl Window {
hovered,
needs_present,
input_rate_tracker,
- #[cfg(feature = "input-latency-histogram")]
- input_latency_tracker: InputLatencyTracker::new()?,
- #[cfg(feature = "frame-duration-histogram")]
- frame_duration_tracker: FrameDurationTracker::new()?,
+ #[cfg(feature = "profiler")]
+ window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
last_input_modality: InputModality::Mouse,
refreshing: false,
activation_observers: SubscriberSet::new(),
@@ -2974,13 +2798,12 @@ impl Window {
/// the contents of the new [`Scene`], use [`Self::present`].
#[profiling::function]
pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
- // Drain unconditionally so a stale first-invalidation timestamp can't
- // leak into a later frame across enable/disable of frame tracing.
+ // Drain every draw in profiler builds so a stale first-invalidation
+ // timestamp can't leak across enable/disable of runtime tracing.
+ #[cfg(feature = "profiler")]
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);
+ #[cfg(feature = "profiler")]
+ self.window_profiler.begin_draw();
// Set up the per-App arena for element allocation during this draw.
// This ensures that multiple test Apps have isolated arenas.
@@ -3088,19 +2911,9 @@ 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,
- });
- }
+ #[cfg(feature = "profiler")]
+ self.window_profiler
+ .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
// Exit the scope to obtain the arena-clear token this draw owes; the
// scope's teardown itself happens in `ElementArenaScope::drop`.
@@ -3132,17 +2945,11 @@ impl Window {
#[profiling::function]
fn present(&mut self) {
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,
- );
- }
+ #[cfg(feature = "profiler")]
+ self.window_profiler.record_present(
+ self.active.get(),
+ !self.next_frame_callbacks.borrow().is_empty(),
+ );
self.needs_present.set(false);
profiling::finish_frame!();
}
@@ -3160,15 +2967,15 @@ impl Window {
}
/// Returns a snapshot of the current input-latency histograms.
- #[cfg(feature = "input-latency-histogram")]
- pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
- self.input_latency_tracker.snapshot()
+ #[cfg(feature = "profiler")]
+ pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
+ self.window_profiler.input_latency_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()
+ #[cfg(feature = "profiler")]
+ pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
+ self.window_profiler.frame_duration_snapshot()
}
fn draw_roots(&mut self, cx: &mut App) {
@@ -5096,8 +4903,8 @@ impl Window {
/// Dispatch a mouse or keyboard event on the window.
#[profiling::function]
pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
- #[cfg(feature = "input-latency-histogram")]
- let dispatch_time = Instant::now();
+ #[cfg(feature = "profiler")]
+ self.window_profiler.begin_input();
let update_count_before = self.invalidator.update_count();
// Track input modality for focus-visible styling and hover suppression.
// Hover is suppressed during keyboard modality so that keyboard navigation
@@ -5224,15 +5031,12 @@ impl Window {
// is the last chance for drag listeners to see the pointer leave and reset their state.
self.promote_external_drag_to_platform(&event, cx);
- if self.invalidator.update_count() > update_count_before {
+ let caused_invalidation = self.invalidator.update_count() > update_count_before;
+ if caused_invalidation {
self.input_rate_tracker.borrow_mut().record_input();
- #[cfg(feature = "input-latency-histogram")]
- if self.invalidator.not_drawing() {
- self.input_latency_tracker.record_input(dispatch_time);
- } else {
- self.input_latency_tracker.record_mid_draw_input();
- }
}
+ #[cfg(feature = "profiler")]
+ self.window_profiler.end_input(caused_invalidation);
DispatchEventResult {
propagate: cx.propagate_event,
@@ -5677,9 +5481,11 @@ impl Window {
.remove(&action.as_any().type_id())
{
for listener in &global_listeners {
- profiler::update_running_action(action, cx);
+ #[cfg(feature = "profiler")]
+ self.window_profiler.begin_action_handler(action, cx);
listener(action.as_any(), DispatchPhase::Capture, cx);
- profiler::save_action_timing();
+ #[cfg(feature = "profiler")]
+ self.window_profiler.end_action_handler();
if !cx.propagate_event {
break;
}
@@ -5709,9 +5515,11 @@ impl Window {
{
let any_action = action.as_any();
if action_type == any_action.type_id() {
- profiler::update_running_action(action, cx);
+ #[cfg(feature = "profiler")]
+ self.window_profiler.begin_action_handler(action, cx);
listener(any_action, DispatchPhase::Capture, self, cx);
- profiler::save_action_timing();
+ #[cfg(feature = "profiler")]
+ self.window_profiler.end_action_handler();
if !cx.propagate_event {
return;
@@ -5731,9 +5539,11 @@ impl Window {
let any_action = action.as_any();
if action_type == any_action.type_id() {
cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
- profiler::update_running_action(action, cx);
+ #[cfg(feature = "profiler")]
+ self.window_profiler.begin_action_handler(action, cx);
listener(any_action, DispatchPhase::Bubble, self, cx);
- profiler::save_action_timing();
+ #[cfg(feature = "profiler")]
+ self.window_profiler.end_action_handler();
if !cx.propagate_event {
return;
@@ -5750,9 +5560,11 @@ impl Window {
for listener in global_listeners.iter().rev() {
cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
- profiler::update_running_action(action, cx);
+ #[cfg(feature = "profiler")]
+ self.window_profiler.begin_action_handler(action, cx);
listener(action.as_any(), DispatchPhase::Bubble, cx);
- profiler::save_action_timing();
+ #[cfg(feature = "profiler")]
+ self.window_profiler.end_action_handler();
if !cx.propagate_event {
break;
}
@@ -7575,105 +7387,4 @@ 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.toml
index 3dd19e08beb..67322ccb37d 100644
--- a/crates/input_latency_ui/Cargo.toml
+++ b/crates/input_latency_ui/Cargo.toml
@@ -14,9 +14,6 @@ path = "src/input_latency_ui.rs"
[dependencies]
chrono.workspace = true
collections.workspace = true
-gpui = { workspace = true, features = [
- "frame-duration-histogram",
- "input-latency-histogram",
-] }
+gpui = { workspace = true, features = ["profiler"] }
hdrhistogram.workspace = true
telemetry.workspace = true
diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.toml
index 37e5dfdafc7..2ccdffb3f67 100644
--- a/crates/zed/Cargo.toml
+++ b/crates/zed/Cargo.toml
@@ -119,8 +119,6 @@ git_ui_core.workspace = true
go_to_line.workspace = true
system_specs.workspace = true
gpui = { workspace = true, features = [
- "frame-duration-histogram",
- "input-latency-histogram",
"profiler",
] }
gpui_platform = {workspace = true, features=["screen-capture", "font-kit", "wayland", "x11"]}
@@ -238,7 +236,7 @@ zlog_settings.workspace = true
etw_tracing.workspace = true
windows.workspace = true
gpui = { workspace = true, features = [
- "input-latency-histogram",
+ "profiler",
"windows-manifest",
] }
@@ -247,7 +245,7 @@ windows_resources = { path = "../windows_resources" }
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
gpui = { workspace = true, features = [
- "input-latency-histogram",
+ "profiler",
"wayland",
"x11",
] }
@@ -266,7 +264,7 @@ activity_indicator = { workspace = true, features = ["test-support"] }
call = { workspace = true, features = ["test-support"] }
editor = { workspace = true, features = ["test-support"] }
fs = { workspace = true, features = ["test-support"] }
-gpui = { workspace = true, features = ["input-latency-histogram", "test-support"] }
+gpui = { workspace = true, features = ["profiler", "test-support"] }
image_viewer = { workspace = true, features = ["test-support"] }
itertools.workspace = true
language = { workspace = true, features = ["test-support"] }