Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Add async task benchmark support (#62180)
Anthony Eid300972bea37c
diff --git a/crates/gpui/src/app/bench_context.rs b/crates/gpui/src/app/bench_context.rsindex 4c68bd50f56..c53a5f088c8 100644--- a/crates/gpui/src/app/bench_context.rs+++ b/crates/gpui/src/app/bench_context.rs@@ -257,6 +257,52 @@ impl Drop for FrameTraceScope {}}+struct MeasuredTaskInput<Input> {+ input: Input,+ frame_trace_scope: Option<FrameTraceScope>,+}++struct MeasuredTaskOutput<Output> {+ frame_trace_scope: Option<FrameTraceScope>,+ report: BenchReport,+ _output: Output,+}++impl<Output> Drop for MeasuredTaskOutput<Output> {+ fn drop(&mut self) {+ let frame_trace_scope = self+ .frame_trace_scope+ .take()+ .expect("measured task output should retain its frame trace scope");+ self.report+ .record_frame_timings(frame_trace_scope.finish().iter());+ }+}++fn run_task_to_completion<Output>(+ foreground_executor: &ForegroundExecutor,+ task: Task<Output>,+) -> Output+where+ Output: 'static,+{+ let output = Rc::new(RefCell::new(None));+ foreground_executor+ .spawn({+ let output = output.clone();+ async move {+ *output.borrow_mut() = Some(task.await);+ }+ })+ .detach();++ foreground_executor+ .dispatcher()+ .as_threaded()+ .expect("BenchAppContext requires a ThreadedDispatcher")+ .run_until(|| output.borrow_mut().take())+}+/// A GPUI app context for Criterion benchmarks.////// `BenchAppContext` is intentionally separate from `TestAppContext`: it owns a@@ -385,6 +431,74 @@ impl<'a, 'measurement> BenchAppContext<'a, 'measurement> {self.replace_bencher(bencher);}+ /// Measures a GPUI task to completion using Criterion's iteration loop.+ ///+ /// The closure is invoked once per Criterion iteration. The returned task+ /// may depend on foreground work, background work, timers, or external+ /// workers that wake GPUI tasks. Its output is dropped after the timed+ /// interval.+ ///+ /// Any window draws triggered by the task are recorded into the benchmark's+ /// frame report through the GPUI frame profiler.+ pub fn bench_task<Output>(&mut self, mut benchmark: impl FnMut(&mut Self) -> Task<Output>)+ where+ Output: 'static,+ {+ self.bench_batched_task_internal("bench_task", |_| (), |_, cx| benchmark(cx));+ }++ /// Measures a GPUI task with per-iteration setup outside the timed interval.+ ///+ /// `setup` runs before timing starts. The returned input is passed by mutable+ /// reference to `benchmark`, which returns the task whose completion is+ /// 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+ /// destruction cannot overlap adjacent measurements.+ pub fn bench_batched_task<Input, Output>(+ &mut self,+ setup: impl FnMut(&mut Self) -> Input,+ benchmark: impl FnMut(&mut Input, &mut Self) -> Task<Output>,+ ) where+ Output: 'static,+ {+ self.bench_batched_task_internal("bench_batched_task", setup, benchmark);+ }++ fn bench_batched_task_internal<Input, Output>(+ &mut self,+ benchmark_kind: &str,+ mut setup: impl FnMut(&mut Self) -> Input,+ mut benchmark: impl FnMut(&mut Input, &mut Self) -> Task<Output>,+ ) where+ Output: 'static,+ {+ let bencher = self.take_bencher(benchmark_kind);+ let mut setup_context = self.clone();+ let mut benchmark_context = self.clone();+ let foreground_executor = self.foreground_executor.clone();+ let report = self.report.clone();++ bencher.iter_batched_ref(+ || MeasuredTaskInput {+ input: setup(&mut setup_context),+ frame_trace_scope: Some(FrameTraceScope::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(),+ report: report.clone(),+ _output: output,+ }+ },+ criterion::BatchSize::PerIteration,+ );+ self.replace_bencher(bencher);+ }+/// Measures frame latency after updating a GPUI entity in its current window.////// Each iteration runs `update` against the entity in its current window. In@@ -779,3 +893,38 @@ impl VisualContext for BenchWindowContext<'_, '_> {})}}++#[cfg(test)]+mod tests {+ use std::{rc::Rc, sync::Arc};++ use super::*;++ #[test]+ fn task_completion_supports_non_send_foreground_output() {+ let dispatcher = Arc::new(ThreadedDispatcher::new());+ let background_executor = BackgroundExecutor::new(dispatcher.clone());+ let foreground_executor = ForegroundExecutor::new(dispatcher);+ let (sender, receiver) = futures::channel::oneshot::channel();++ background_executor+ .spawn(async move {+ sender+ .send(())+ .expect("foreground receiver should remain alive");+ })+ .detach();+ let expected_output = Rc::new(42);+ let task_output = expected_output.clone();+ let task = foreground_executor.spawn(async move {+ receiver.await.expect("background task should send a value");+ task_output+ });++ let output = run_task_to_completion(&foreground_executor, task);+ assert!(+ Rc::ptr_eq(&output, &expected_output),+ "task runner should preserve non-Send foreground output"+ );+ }+}diff --git a/crates/gpui/src/platform/threaded_dispatcher.rs b/crates/gpui/src/platform/threaded_dispatcher.rsindex be130691dab..db11f3542fd 100644--- a/crates/gpui/src/platform/threaded_dispatcher.rs+++ b/crates/gpui/src/platform/threaded_dispatcher.rs@@ -257,6 +257,31 @@ impl ThreadedDispatcher {}}+ /// Drives main-thread work until `ready` returns a value.+ ///+ /// Unlike [`Self::run_until_idle`], this waits across temporary quiescence.+ /// This is required when completion can arrive from an external worker that+ /// is not represented in the dispatcher's in-flight count.+ #[cfg(any(test, feature = "bench"))]+ pub(crate) fn run_until<R>(&self, mut ready: impl FnMut() -> Option<R>) -> R {+ assert!(+ self.is_main_thread(),+ "run_until must be called on the threaded dispatcher's main thread"+ );+ loop {+ self.drain_main_queue();+ if let Some(result) = ready() {+ return result;+ }++ let mut inflight = self.idle.inflight.lock();+ if self.main_queue_has_work() {+ continue;+ }+ self.idle.condvar.wait(&mut inflight);+ }+ }+/// Runs all main-thread tasks that are queued right now, without waiting for/// background work or timers to finish.pub fn run_ready_main_tasks(&self) -> bool {@@ -449,6 +474,36 @@ mod tests {assert!(completed.load(Ordering::SeqCst));}+ #[test]+ fn run_until_waits_for_untracked_external_wakes() {+ let dispatcher = Arc::new(ThreadedDispatcher::new());+ let foreground = ForegroundExecutor::new(dispatcher.clone());+ let (sender, receiver) = futures::channel::oneshot::channel();+ let sender_thread = thread::spawn(move || {+ thread::sleep(Duration::from_millis(10));+ sender+ .send(())+ .expect("foreground receiver should remain alive");+ });++ let completed = Arc::new(AtomicBool::new(false));+ foreground+ .spawn({+ let completed = completed.clone();+ async move {+ receiver+ .await+ .expect("external sender should deliver its wake");+ completed.store(true, Ordering::SeqCst);+ }+ })+ .detach();++ dispatcher.run_until(|| completed.load(Ordering::SeqCst).then_some(()));+ sender_thread.join().expect("sender thread should finish");+ assert!(completed.load(Ordering::SeqCst));+ }+#[test]fn timers_fire_in_real_time() {let dispatcher = Arc::new(ThreadedDispatcher::new());