Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf(desktop-gpui): add a timeline draw benchmark for the editor window
Abdeslam Yassine Agmar1a285b2575e0
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rsindex 563781960..63f4ce9f2 100644--- a/apps/desktop-gpui/src/app_windows.rs+++ b/apps/desktop-gpui/src/app_windows.rs@@ -5345,6 +5345,7 @@ fn load_editor_project_candidate(drive_auto_sidebar(handle, cx).await;drive_auto_playback(path, handle, cx).await;+ crate::editor_bench::run(handle, cx).await;drive_auto_export(handle, cx).await;}).detach();diff --git a/apps/desktop-gpui/src/camera_bench.rs b/apps/desktop-gpui/src/camera_bench.rsindex 79b79d343..9fb27fba9 100644--- a/apps/desktop-gpui/src/camera_bench.rs+++ b/apps/desktop-gpui/src/camera_bench.rs@@ -16,7 +16,10 @@ use std::time::{Duration, Instant};use gpui::App;-use crate::app_windows::{self, AppWindows};+use crate::{+ app_windows::{self, AppWindows},+ draw_bench,+};const FRAME_WIDTH: usize = 1280;const FRAME_HEIGHT: usize = 720;@@ -43,7 +46,7 @@ pub fn run(cx: &mut App) {let frame = native_frame(&sources[index % sources.len()]);let delivered = cx.update(|cx| {let delivered = app_windows::deliver_camera_frame(frame, cx);- let _ = draw_camera_window(handle, cx);+ let _ = draw_bench::timed_draw(handle.into(), cx);delivered});if !delivered {@@ -58,7 +61,7 @@ pub fn run(cx: &mut App) {let frame = native_frame(&sources[index % sources.len()]);let elapsed = cx.update(|cx| {app_windows::deliver_camera_frame(frame, cx);- draw_camera_window(handle, cx)+ draw_bench::timed_draw(handle.into(), cx)});if let Some(elapsed) = elapsed {draw_us.push(elapsed.as_secs_f64() * 1e6);@@ -79,7 +82,7 @@ pub fn run(cx: &mut App) {let mut clean_us = Vec::with_capacity(MEASURED_FRAMES);for _ in 0..MEASURED_FRAMES {cx.background_executor().timer(interval).await;- let elapsed = cx.update(|cx| draw_camera_window(handle, cx));+ let elapsed = cx.update(|cx| draw_bench::timed_draw(handle.into(), cx));if let Some(elapsed) = elapsed {clean_us.push(elapsed.as_secs_f64() * 1e6);}@@ -89,40 +92,13 @@ pub fn run(cx: &mut App) {"camera-bench: {} frames at {FPS}fps ({FRAME_WIDTH}x{FRAME_HEIGHT} 420v camera frames)",draw_us.len());- report("frame draw", &mut draw_us);- report("clean draw", &mut clean_us);+ draw_bench::report("camera-bench", "frame draw", &mut draw_us);+ draw_bench::report("camera-bench", "clean draw", &mut clean_us);std::process::exit(0);}).detach();}-fn report(label: &str, samples: &mut [f64]) {- samples.sort_by(|a, b| a.partial_cmp(b).expect("no NaN draw times"));- let mean = samples.iter().sum::<f64>() / samples.len() as f64;- let p50 = samples[samples.len() / 2];- let p95 = samples[(samples.len() as f64 * 0.95) as usize];- let max = samples[samples.len() - 1];- println!(- "camera-bench: {label} {mean:.1} mean / {p50:.1} p50 / {p95:.1} p95 / {max:.1} max us"- );-}--/// One synchronous `Window::draw`, timed. `AnyWindowHandle::update` passes the-/// root as an unleased `AnyView`; the typed handle would lease the root entity-/// that `draw()` re-renders.-fn draw_camera_window(- handle: gpui::WindowHandle<crate::camera_window::CameraWindow>,- cx: &mut App,-) -> Option<Duration> {- gpui::AnyWindowHandle::from(handle)- .update(cx, |_, window, cx| {- let started = Instant::now();- window.draw(cx).clear();- started.elapsed()- })- .ok()-}-fn native_frame(sample_buf: &cidre::arc::R<cidre::cm::SampleBuf>,) -> cap_recording::NativeCameraFrame {diff --git a/apps/desktop-gpui/src/draw_bench.rs b/apps/desktop-gpui/src/draw_bench.rsnew file mode 100644index 000000000..efbc8ae8a--- /dev/null+++ b/apps/desktop-gpui/src/draw_bench.rs@@ -0,0 +1,25 @@+use std::time::{Duration, Instant};++use gpui::{AnyWindowHandle, App};++/// One synchronous `Window::draw`, timed. `AnyWindowHandle::update` passes the+/// root as an unleased `AnyView`; the typed handle would lease the root entity+/// that `draw()` re-renders.+pub(crate) fn timed_draw(handle: AnyWindowHandle, cx: &mut App) -> Option<Duration> {+ handle+ .update(cx, |_, window, cx| {+ let started = Instant::now();+ window.draw(cx).clear();+ started.elapsed()+ })+ .ok()+}++pub(crate) fn report(prefix: &str, label: &str, samples: &mut [f64]) {+ samples.sort_by(|a, b| a.partial_cmp(b).expect("no NaN draw times"));+ let mean = samples.iter().sum::<f64>() / samples.len() as f64;+ let p50 = samples[samples.len() / 2];+ let p95 = samples[(samples.len() as f64 * 0.95) as usize];+ let max = samples[samples.len() - 1];+ println!("{prefix}: {label} {mean:.1} mean / {p50:.1} p50 / {p95:.1} p95 / {max:.1} max us");+}diff --git a/apps/desktop-gpui/src/editor_bench.rs b/apps/desktop-gpui/src/editor_bench.rsnew file mode 100644index 000000000..a72196707--- /dev/null+++ b/apps/desktop-gpui/src/editor_bench.rs@@ -0,0 +1,188 @@+//! Needs a clip of at least 30 s so the `follow` scenario does not run off the+//! end. Run from `apps/desktop-gpui`:+//! CAP_GPUI_AUTO_EDITOR=<studio .cap> CAP_GPUI_AUTO_TIMELINE_BENCH=1 \+//! CAP_GPUI_NO_MENUS=1 CAP_GPUI_NO_TRAY=1 CAP_GPUI_MUTE_AUDIO=1 \+//! cargo run --release++use std::time::{Duration, Instant};++use gpui::{AsyncApp, Context, Window, WindowHandle};++use crate::{draw_bench, editor_timeline, editor_window::EditorWindow};++const WARMUP_FRAMES: usize = 60;+const MEASURED_FRAMES: usize = 300;+const FRAME_INTERVAL: Duration = Duration::from_millis(16);+const READY_POLL: Duration = Duration::from_millis(50);+const READY_TIMEOUT: Duration = Duration::from_secs(30);+const FOLLOW_ZOOM_SECS: f64 = 20.0;+const FOLLOW_START_FRACTION: f64 = 0.82;++#[derive(Clone, Copy)]+enum Scenario {+ Tick,+ TickZoomedOut,+ Hover,+ Follow,+ Clean,+}++impl Scenario {+ fn label(self) -> &'static str {+ match self {+ Self::Tick => "tick",+ Self::TickZoomedOut => "tick-zoomed-out",+ Self::Hover => "hover",+ Self::Follow => "follow",+ Self::Clean => "clean",+ }+ }++ fn prepare(self, view: &mut EditorWindow, window: &mut Window, cx: &mut Context<EditorWindow>) {+ match self {+ Self::Tick => {+ if !view.playing {+ view.toggle_play(window, cx);+ }+ }+ Self::TickZoomedOut => {+ view.bench_zoom_to(view.total_duration(), cx);+ if !view.playing {+ view.toggle_play(window, cx);+ }+ }+ Self::Hover => {+ if view.playing {+ view.stop_for_measurement(cx);+ }+ view.bench_zoom_to(view.total_duration(), cx);+ view.seek_fraction(0., window, cx);+ }+ Self::Follow => {+ if view.playing {+ view.stop_for_measurement(cx);+ }+ view.bench_zoom_to(FOLLOW_ZOOM_SECS, cx);+ view.seek_fraction(FOLLOW_START_FRACTION, window, cx);+ view.toggle_play(window, cx);+ }+ Self::Clean => {+ if view.playing {+ view.stop_for_measurement(cx);+ }+ view.bench_zoom_to(view.total_duration(), cx);+ }+ }+ }++ fn step(+ self,+ iteration: usize,+ view: &mut EditorWindow,+ window: &mut Window,+ cx: &mut Context<EditorWindow>,+ ) {+ match self {+ Self::Tick | Self::TickZoomedOut | Self::Follow => {+ view.invalidate_playback_chrome(window, cx)+ }+ Self::Hover => {+ let viewport_width: f32 = window.viewport_size().width.into();+ let fraction = iteration as f32 / (WARMUP_FRAMES + MEASURED_FRAMES) as f32;+ let x = editor_timeline::content_left()+ + editor_timeline::content_width(viewport_width) * fraction;+ view.timeline_hover(x, window, cx);+ }+ Self::Clean => {}+ }+ }+}++pub(crate) async fn run(handle: WindowHandle<EditorWindow>, cx: &mut AsyncApp) {+ if !std::env::var("CAP_GPUI_AUTO_TIMELINE_BENCH").is_ok_and(|value| value == "1") {+ return;+ }++ let started = Instant::now();+ loop {+ let ready = handle+ .update(cx, |view, _, _| {+ let (mic, system) = view.has_waveforms();+ view.latest_frame.is_some() && (mic || system)+ })+ .unwrap_or(false);+ if ready {+ break;+ }+ if started.elapsed() > READY_TIMEOUT {+ eprintln!(+ "timeline-bench: no rendered frame and waveforms within {}s",+ READY_TIMEOUT.as_secs()+ );+ std::process::exit(1);+ }+ cx.background_executor().timer(READY_POLL).await;+ }++ let Ok(header) = handle.update(cx, |view, window, _| {+ let viewport_width: f32 = window.viewport_size().width.into();+ let content_width = editor_timeline::content_width(viewport_width);+ let (mic, system) = view.has_waveforms();+ format!(+ "timeline-bench: viewport {viewport_width:.0}px, content {content_width:.0}px, \+ clip {:.1}s, mic {mic}, system {system}, target {} samples/path",+ view.total_duration(),+ editor_timeline::waveform_sample_count(f64::from(content_width)),+ )+ }) else {+ eprintln!("timeline-bench: the editor window closed");+ std::process::exit(1);+ };+ println!("{header}");++ for scenario in [+ Scenario::Tick,+ Scenario::TickZoomedOut,+ Scenario::Hover,+ Scenario::Follow,+ Scenario::Clean,+ ] {+ if handle+ .update(cx, |view, window, cx| scenario.prepare(view, window, cx))+ .is_err()+ {+ eprintln!("timeline-bench: the editor window closed");+ std::process::exit(1);+ }++ let mut draw_us = Vec::with_capacity(MEASURED_FRAMES);+ for iteration in 0..WARMUP_FRAMES + MEASURED_FRAMES {+ cx.background_executor().timer(FRAME_INTERVAL).await;+ let elapsed = cx.update(|cx| {+ handle+ .update(cx, |view, window, cx| {+ scenario.step(iteration, view, window, cx)+ })+ .ok()?;+ draw_bench::timed_draw(handle.into(), cx)+ });+ if iteration >= WARMUP_FRAMES+ && let Some(elapsed) = elapsed+ {+ draw_us.push(elapsed.as_secs_f64() * 1e6);+ }+ }++ if draw_us.len() < MEASURED_FRAMES {+ eprintln!(+ "timeline-bench: only {} of {MEASURED_FRAMES} {} draws completed",+ draw_us.len(),+ scenario.label()+ );+ std::process::exit(1);+ }+ draw_bench::report("timeline-bench", scenario.label(), &mut draw_us);+ }++ std::process::exit(0);+}diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rsindex 5270dcd1f..7484cb3ce 100644--- a/apps/desktop-gpui/src/editor_window.rs+++ b/apps/desktop-gpui/src/editor_window.rs@@ -3298,6 +3298,22 @@ impl EditorWindow {self.stop_playback(cx);}+ pub(crate) fn has_waveforms(&self) -> (bool, bool) {+ let present = |tables: &[Arc<Vec<f32>>]| tables.iter().any(|peaks| !peaks.is_empty());+ (+ present(&self.timeline.mic_waveforms),+ present(&self.timeline.system_waveforms),+ )+ }++ pub(crate) fn bench_zoom_to(&mut self, seconds: f64, cx: &mut Context<Self>) {+ let total = self.total_duration();+ self.view+ .transform+ .update_zoom(seconds, self.playhead, total);+ cx.notify();+ }+fn capture_playback_key(&mut self,event: &gpui::KeyDownEvent,@@ -3741,7 +3757,11 @@ impl EditorWindow {cx.notify();}- fn invalidate_playback_chrome(&mut self, _window: &mut Window, cx: &mut Context<Self>) {+ pub(crate) fn invalidate_playback_chrome(+ &mut self,+ _window: &mut Window,+ cx: &mut Context<Self>,+ ) {self.timeline_view.update(cx, |_, cx| cx.notify());self.transport_controls.update(cx, |_, cx| cx.notify());// While playing, nothing else the parent renders reads the playhead:@@ -3775,7 +3795,7 @@ impl EditorWindow {/// `onMouseMove` on the timeline container (`TL/index.tsx:1170-1188`):/// while paused, the pointer's time becomes `previewTime`; outside the/// content column, and at all times while playing, it is cleared.- fn timeline_hover(&mut self, x: f32, window: &mut Window, cx: &mut Context<Self>) {+ pub(crate) fn timeline_hover(&mut self, x: f32, window: &mut Window, cx: &mut Context<Self>) {// `if (editorState.playing) return;` -- the handler bails *before* it// writes, so a preview time set while paused survives a play rather// than being cleared. The ghost is hidden by the render's owndiff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rsindex 98a6b1b2b..6ff3d707d 100644--- a/apps/desktop-gpui/src/main.rs+++ b/apps/desktop-gpui/src/main.rs@@ -19,7 +19,9 @@ mod deeplink;mod dev_restore;mod devices;mod diagnostics;+mod draw_bench;mod editor_audio;+mod editor_bench;mod editor_canvas;mod editor_clips;mod editor_color;