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: Add bare bones benchmark framework (#58191)

Anthony Eidaa6f03bedd56
diff --git a/crates/editor/benches/editor_render.rs b/crates/editor/benches/editor_render.rs
index e93c94e1ae6..2840d782bd5 100644
--- a/crates/editor/benches/editor_render.rs
+++ b/crates/editor/benches/editor_render.rs
@@ -3,18 +3,20 @@ use editor::{
Editor, EditorMode, MultiBuffer,
actions::{DeleteToPreviousWordStart, SelectAll, SplitSelectionIntoLines},
};
-use gpui::{AppContext, Focusable as _, TestAppContext, TestDispatcher};
+use gpui::{AppContext as _, BenchAppContext, Focusable as _, TestAppContext, TestDispatcher};
use rand::{Rng as _, SeedableRng as _, rngs::StdRng};
use settings::SettingsStore;
use ui::IntoElement;
use util::RandomCharIter;
-fn editor_input_with_1000_cursors(bencher: &mut Bencher<'_>, cx: &TestAppContext) {
- let mut cx = cx.clone();
+#[gpui::bench]
+fn editor_input_with_1000_cursors(bencher: &mut Bencher<'_>, cx: &mut BenchAppContext) {
+ init_context(cx);
+
let text = String::from_iter(["line:\n"; 1000]);
let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
- let cx = cx.add_empty_window();
+ let mut cx = cx.add_empty_window();
let editor = cx.update(|window, cx| {
let editor = cx.new(|cx| {
let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
@@ -63,10 +65,10 @@ fn open_editor_with_one_long_line(bencher: &mut Bencher<'_>, args: &(String, Tes
let mut cx = cx.clone();
bencher.iter(|| {
- let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
+ let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
let cx = cx.add_empty_window();
- let _ = cx.update(|window, cx| {
+ cx.update(|window, cx| {
let editor = cx.new(|cx| {
let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
editor.set_style(editor::EditorStyle::default(), window, cx);
@@ -106,7 +108,6 @@ fn editor_render(bencher: &mut Bencher<'_>, cx: &TestAppContext) {
bencher.iter(|| {
cx.update(|window, cx| {
- // editor.update(cx, |editor, cx| editor.move_down(&MoveDown, window, cx));
let mut view = editor.clone().into_any_element();
let _ = view.request_layout(window, cx);
let _ = view.prepaint(window, cx);
@@ -115,53 +116,49 @@ fn editor_render(bencher: &mut Bencher<'_>, cx: &TestAppContext) {
})
}
-pub fn benches() {
- let dispatcher = TestDispatcher::new(1);
- let cx = gpui::TestAppContext::build(dispatcher, None);
+fn init_context(cx: &mut BenchAppContext) {
+ cx.update(|cx| {
+ let store = SettingsStore::test(cx);
+ cx.set_global(store);
+ assets::Assets.load_test_fonts(cx);
+ theme_settings::init(theme::LoadThemes::JustBase, cx);
+ editor::init(cx);
+ });
+}
+
+fn init_test_context(cx: &TestAppContext) {
cx.update(|cx| {
let store = SettingsStore::test(cx);
cx.set_global(store);
assets::Assets.load_test_fonts(cx);
theme_settings::init(theme::LoadThemes::JustBase, cx);
- // release_channel::init(semver::Version::new(0,0,0), cx);
editor::init(cx);
});
+}
- let mut criterion: criterion::Criterion<_> =
- (criterion::Criterion::default()).configure_from_args();
+fn criterion_benches(criterion: &mut criterion::Criterion) {
+ let dispatcher = TestDispatcher::new(1);
+ let cx = gpui::TestAppContext::build(dispatcher, None);
+ init_test_context(&cx);
- // setup app context
let mut group = criterion.benchmark_group("Time to render");
group.bench_with_input(
BenchmarkId::new("editor_render", "TestAppContext"),
&cx,
editor_render,
);
-
group.finish();
let text = String::from_iter(["char"; 1000]);
+ let input = (text, cx.clone());
let mut group = criterion.benchmark_group("Build buffer with one long line");
group.bench_with_input(
BenchmarkId::new("editor_with_one_long_line", "(String, TestAppContext )"),
- &(text, cx.clone()),
+ &input,
open_editor_with_one_long_line,
);
-
- group.finish();
-
- let mut group = criterion.benchmark_group("multi cursor edits");
- group.bench_with_input(
- BenchmarkId::new("editor_input_with_1000_cursors", "TestAppContext"),
- &cx,
- editor_input_with_1000_cursors,
- );
group.finish();
}
-fn main() {
- benches();
- criterion::Criterion::default()
- .configure_from_args()
- .final_summary();
-}
+gpui::bench_group!(benches, editor_input_with_1000_cursors, criterion_benches);
+gpui::bench_main!(benches);
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
index c8f1032fbd9..71b5b258bda 100644
--- a/crates/gpui/src/app.rs
+++ b/crates/gpui/src/app.rs
@@ -23,6 +23,8 @@ use parking_lot::RwLock;
use slotmap::SlotMap;
pub use async_context::*;
+#[cfg(any(test, feature = "test-support"))]
+pub use bench_context::{BenchAppContext, BenchWindowContext};
use collections::{FxHashMap, FxHashSet, HashMap, VecDeque};
pub use context::*;
pub use entity_map::*;
@@ -56,6 +58,8 @@ use crate::{
};
mod async_context;
+#[cfg(any(test, feature = "test-support"))]
+mod bench_context;
mod context;
mod entity_map;
#[cfg(any(test, feature = "test-support"))]
diff --git a/crates/gpui/src/app/bench_context.rs b/crates/gpui/src/app/bench_context.rs
new file mode 100644
index 00000000000..6af1b7a9fa9
--- /dev/null
+++ b/crates/gpui/src/app/bench_context.rs
@@ -0,0 +1,387 @@
+use std::{future::Future, rc::Rc, sync::Arc};
+
+use anyhow::{Result, anyhow};
+
+use crate::{
+ AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, Bounds, Context, Empty,
+ Entity, EntityId, Focusable, ForegroundExecutor, Global, Render, Reservation, Task,
+ TestDispatcher, TestPlatform, VisualContext, Window, WindowBounds, WindowHandle, WindowOptions,
+ app::{GpuiBorrow, GpuiMode},
+};
+
+/// A GPUI app context for Criterion benchmarks.
+///
+/// `BenchAppContext` is intentionally separate from `TestAppContext`: it owns a
+/// benchmark app instance and exposes only the app/window operations needed by
+/// benchmark setup. Criterion remains responsible for the measured loop via its
+/// `Bencher` API.
+#[derive(Clone)]
+pub struct BenchAppContext {
+ app: Rc<AppCell>,
+ background_executor: BackgroundExecutor,
+ foreground_executor: ForegroundExecutor,
+ dispatcher: TestDispatcher,
+ benchmark_name: Option<&'static str>,
+}
+
+impl BenchAppContext {
+ /// Creates a new benchmark app context.
+ pub fn new(benchmark_name: Option<&'static str>) -> Self {
+ Self::with_seed(benchmark_name, 0)
+ }
+
+ /// Creates a new benchmark app context with the provided scheduler seed.
+ pub fn with_seed(benchmark_name: Option<&'static str>, seed: u64) -> Self {
+ Self::build(TestDispatcher::new(seed), benchmark_name)
+ }
+
+ fn build(dispatcher: TestDispatcher, benchmark_name: Option<&'static str>) -> Self {
+ let dispatcher = Arc::new(dispatcher);
+ let background_executor = BackgroundExecutor::new(dispatcher.clone());
+ let foreground_executor = ForegroundExecutor::new(dispatcher.clone());
+ let platform = TestPlatform::new(background_executor.clone(), foreground_executor.clone());
+ let asset_source = Arc::new(());
+ let http_client = http_client::FakeHttpClient::with_404_response();
+ let app = App::new_app(platform, asset_source, http_client);
+ app.borrow_mut().mode = GpuiMode::test();
+
+ Self {
+ app,
+ background_executor,
+ foreground_executor,
+ dispatcher: (*dispatcher).clone(),
+ benchmark_name,
+ }
+ }
+
+ /// The benchmark function name that created this context.
+ pub fn benchmark_name(&self) -> Option<&'static str> {
+ self.benchmark_name
+ }
+
+ /// Returns the background executor used by this benchmark app.
+ pub fn background_executor(&self) -> &BackgroundExecutor {
+ &self.background_executor
+ }
+
+ /// Returns the foreground executor used by this benchmark app.
+ pub fn foreground_executor(&self) -> &ForegroundExecutor {
+ &self.foreground_executor
+ }
+
+ /// Runs pending scheduled work until the benchmark app is idle.
+ pub fn run_until_idle(&self) {
+ self.dispatcher.run_until_parked();
+ }
+
+ /// Updates the app and flushes synchronous GPUI effects afterward.
+ pub fn update<R>(&mut self, update: impl FnOnce(&mut App) -> R) -> R {
+ let mut app = self.app.borrow_mut();
+ app.update(update)
+ }
+
+ /// Reads app state.
+ pub fn read<R>(&self, read: impl FnOnce(&App) -> R) -> R {
+ let app = self.app.borrow();
+ read(&app)
+ }
+
+ /// Adds a window with an empty root view for benchmark setup.
+ pub fn add_empty_window(&mut self) -> BenchWindowContext {
+ let window = {
+ let mut app = self.app.borrow_mut();
+ let bounds = Bounds::maximized(None, &app);
+ let window: AnyWindowHandle = app
+ .open_window(
+ WindowOptions {
+ window_bounds: Some(WindowBounds::Windowed(bounds)),
+ ..Default::default()
+ },
+ |_, cx| cx.new(|_| Empty),
+ )
+ .expect("failed to open benchmark window")
+ .into();
+ window
+ };
+
+ self.run_until_idle();
+ BenchWindowContext {
+ cx: self.clone(),
+ window,
+ }
+ }
+
+ /// Runs GPUI benchmark teardown.
+ pub fn teardown(mut self) {
+ self.run_until_idle();
+ self.update(|cx| {
+ cx.background_executor().forbid_parking();
+ cx.quit();
+ });
+ self.run_until_idle();
+ }
+}
+
+impl AppContext for BenchAppContext {
+ fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
+ let mut app = self.app.borrow_mut();
+ app.new(build_entity)
+ }
+
+ fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
+ let mut app = self.app.borrow_mut();
+ app.reserve_entity()
+ }
+
+ fn insert_entity<T: 'static>(
+ &mut self,
+ reservation: Reservation<T>,
+ build_entity: impl FnOnce(&mut Context<T>) -> T,
+ ) -> Entity<T> {
+ let mut app = self.app.borrow_mut();
+ app.insert_entity(reservation, build_entity)
+ }
+
+ fn update_entity<T: 'static, R>(
+ &mut self,
+ handle: &Entity<T>,
+ update: impl FnOnce(&mut T, &mut Context<T>) -> R,
+ ) -> R {
+ let mut app = self.app.borrow_mut();
+ app.update_entity(handle, update)
+ }
+
+ fn as_mut<'a, T>(&'a mut self, _: &Entity<T>) -> GpuiBorrow<'a, T>
+ where
+ T: 'static,
+ {
+ panic!("Cannot use as_mut with BenchAppContext. Call update() instead.")
+ }
+
+ fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
+ where
+ T: 'static,
+ {
+ let app = self.app.borrow();
+ app.read_entity(handle, read)
+ }
+
+ fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
+ where
+ F: FnOnce(AnyView, &mut Window, &mut App) -> T,
+ {
+ let mut app = self.app.borrow_mut();
+ app.update_window(window, update)
+ }
+
+ fn with_window<R>(
+ &mut self,
+ entity_id: EntityId,
+ update: impl FnOnce(&mut Window, &mut App) -> R,
+ ) -> Option<R> {
+ let mut app = self.app.borrow_mut();
+ app.with_window(entity_id, update)
+ }
+
+ fn read_window<T, R>(
+ &self,
+ window: &WindowHandle<T>,
+ read: impl FnOnce(Entity<T>, &App) -> R,
+ ) -> Result<R>
+ where
+ T: 'static,
+ {
+ let app = self.app.borrow();
+ app.read_window(window, read)
+ }
+
+ fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
+ where
+ R: Send + 'static,
+ {
+ self.background_executor.spawn(future)
+ }
+
+ fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
+ where
+ G: Global,
+ {
+ let app = self.app.borrow();
+ app.read_global(callback)
+ }
+}
+
+/// A window-specific context for GPUI benchmarks.
+///
+/// This is separate from `VisualTestContext`; it provides access to a benchmark
+/// window without exposing test-only helpers such as input simulation.
+#[derive(Clone)]
+pub struct BenchWindowContext {
+ cx: BenchAppContext,
+ window: AnyWindowHandle,
+}
+
+impl BenchWindowContext {
+ /// Returns the underlying benchmark app context.
+ pub fn app_context(&mut self) -> &mut BenchAppContext {
+ &mut self.cx
+ }
+
+ /// Returns the window associated with this context.
+ pub fn window_handle(&self) -> AnyWindowHandle {
+ self.window
+ }
+
+ /// Updates the benchmark window.
+ pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> R {
+ self.cx
+ .update_window(self.window, |_, window, cx| update(window, cx))
+ .expect("benchmark window was unexpectedly closed")
+ }
+
+ /// Runs pending scheduled work until the benchmark app is idle.
+ pub fn run_until_idle(&self) {
+ self.cx.run_until_idle();
+ }
+}
+
+impl AppContext for BenchWindowContext {
+ fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
+ self.window
+ .update(&mut self.cx, |_, _, cx| cx.new(build_entity))
+ .expect("benchmark window was unexpectedly closed")
+ }
+
+ fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
+ self.cx.reserve_entity()
+ }
+
+ fn insert_entity<T: 'static>(
+ &mut self,
+ reservation: Reservation<T>,
+ build_entity: impl FnOnce(&mut Context<T>) -> T,
+ ) -> Entity<T> {
+ self.window
+ .update(&mut self.cx, |_, _, cx| {
+ cx.insert_entity(reservation, build_entity)
+ })
+ .expect("benchmark window was unexpectedly closed")
+ }
+
+ fn update_entity<T: 'static, R>(
+ &mut self,
+ handle: &Entity<T>,
+ update: impl FnOnce(&mut T, &mut Context<T>) -> R,
+ ) -> R {
+ self.cx.update_entity(handle, update)
+ }
+
+ fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
+ where
+ T: 'static,
+ {
+ self.cx.as_mut(handle)
+ }
+
+ fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
+ where
+ T: 'static,
+ {
+ self.cx.read_entity(handle, read)
+ }
+
+ fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
+ where
+ F: FnOnce(AnyView, &mut Window, &mut App) -> T,
+ {
+ self.cx.update_window(window, update)
+ }
+
+ fn with_window<R>(
+ &mut self,
+ entity_id: EntityId,
+ update: impl FnOnce(&mut Window, &mut App) -> R,
+ ) -> Option<R> {
+ self.cx.with_window(entity_id, update)
+ }
+
+ fn read_window<T, R>(
+ &self,
+ window: &WindowHandle<T>,
+ read: impl FnOnce(Entity<T>, &App) -> R,
+ ) -> Result<R>
+ where
+ T: 'static,
+ {
+ self.cx.read_window(window, read)
+ }
+
+ fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
+ where
+ R: Send + 'static,
+ {
+ self.cx.background_spawn(future)
+ }
+
+ fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
+ where
+ G: Global,
+ {
+ self.cx.read_global(callback)
+ }
+}
+
+impl VisualContext for BenchWindowContext {
+ type Result<T> = Result<T>;
+
+ fn window_handle(&self) -> AnyWindowHandle {
+ self.window
+ }
+
+ fn update_window_entity<T: 'static, R>(
+ &mut self,
+ entity: &Entity<T>,
+ update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
+ ) -> Result<R> {
+ let entity = entity.clone();
+ self.cx
+ .app
+ .borrow_mut()
+ .with_window(entity.entity_id(), |window, app| {
+ entity.update(app, |entity, cx| update(entity, window, cx))
+ })
+ .ok_or_else(|| {
+ anyhow!("entity has no current window; use `update` instead of `update_in`")
+ })
+ }
+
+ fn new_window_entity<T: 'static>(
+ &mut self,
+ build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
+ ) -> Result<Entity<T>> {
+ self.window.update(&mut self.cx, |_, window, cx| {
+ cx.new(|cx| build_entity(window, cx))
+ })
+ }
+
+ fn replace_root_view<V>(
+ &mut self,
+ build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V,
+ ) -> Result<Entity<V>>
+ where
+ V: 'static + Render,
+ {
+ self.window.update(&mut self.cx, |_, window, cx| {
+ window.replace_root(cx, build_view)
+ })
+ }
+
+ fn focus<V>(&mut self, entity: &Entity<V>) -> Result<()>
+ where
+ V: Focusable,
+ {
+ self.window.update(&mut self.cx, |_, window, cx| {
+ entity.read(cx).focus_handle(cx).focus(window, cx)
+ })
+ }
+}
diff --git a/crates/gpui/src/gpui.rs b/crates/gpui/src/gpui.rs
index 12aeebfb956..b792718f881 100644
--- a/crates/gpui/src/gpui.rs
+++ b/crates/gpui/src/gpui.rs
@@ -94,8 +94,32 @@ pub use executor::*;
pub use geometry::*;
pub use global::*;
pub use gpui_macros::{
- AppContext, IntoElement, Render, VisualContext, property_test, register_action, test,
+ AppContext, IntoElement, Render, VisualContext, bench, property_test, register_action, test,
};
+
+/// Defines a Criterion benchmark group for benchmarks annotated with [`gpui::bench`].
+///
+/// This mirrors `criterion::criterion_group!` so GPUI benchmark files can keep the
+/// same shape as ordinary Criterion benchmarks.
+///
+/// [`gpui::bench`]: crate::bench
+#[macro_export]
+macro_rules! bench_group {
+ ($($tokens:tt)*) => {
+ criterion::criterion_group!($($tokens)*);
+ };
+}
+
+/// Defines the entry point for GPUI Criterion benchmark groups.
+///
+/// This mirrors `criterion::criterion_main!` so GPUI benchmark files can keep the
+/// same shape as ordinary Criterion benchmarks.
+#[macro_export]
+macro_rules! bench_main {
+ ($($tokens:tt)*) => {
+ criterion::criterion_main!($($tokens)*);
+ };
+}
pub use gpui_shared_string::*;
pub use gpui_util::arc_cow::ArcCow;
pub use http_client;
diff --git a/crates/gpui_macros/src/bench.rs b/crates/gpui_macros/src/bench.rs
new file mode 100644
index 00000000000..7d7b2ad8939
--- /dev/null
+++ b/crates/gpui_macros/src/bench.rs
@@ -0,0 +1,45 @@
+use proc_macro::TokenStream;
+use quote::{format_ident, quote};
+use syn::{ItemFn, spanned::Spanned};
+
+pub fn bench(args: TokenStream, function: TokenStream) -> TokenStream {
+ if !args.is_empty() {
+ return error_to_stream(syn::Error::new(
+ proc_macro2::TokenStream::from(args).span(),
+ "#[gpui::bench] does not accept arguments yet",
+ ));
+ }
+
+ let mut inner_fn = match syn::parse::<ItemFn>(function) {
+ Ok(function) => function,
+ Err(error) => return error_to_stream(error),
+ };
+
+ if let Some(asyncness) = &inner_fn.sig.asyncness {
+ return error_to_stream(syn::Error::new(
+ asyncness.span(),
+ "#[gpui::bench] does not support async benchmark functions yet",
+ ));
+ }
+
+ let outer_fn_name = inner_fn.sig.ident.clone();
+ let inner_fn_name = format_ident!("__gpui_bench_{}", outer_fn_name);
+ inner_fn.sig.ident = inner_fn_name.clone();
+
+ TokenStream::from(quote! {
+ #inner_fn
+
+ fn #outer_fn_name(criterion: &mut criterion::Criterion) {
+ criterion.bench_function(stringify!(#outer_fn_name), |bencher| {
+ let mut cx = gpui::BenchAppContext::new(Some(stringify!(#outer_fn_name)));
+ #inner_fn_name(bencher, &mut cx);
+ cx.teardown();
+ });
+ }
+
+ })
+}
+
+fn error_to_stream(error: syn::Error) -> TokenStream {
+ TokenStream::from(error.into_compile_error())
+}
diff --git a/crates/gpui_macros/src/gpui_macros.rs b/crates/gpui_macros/src/gpui_macros.rs
index e30c85e6edb..1fe3fa97eae 100644
--- a/crates/gpui_macros/src/gpui_macros.rs
+++ b/crates/gpui_macros/src/gpui_macros.rs
@@ -1,3 +1,4 @@
+mod bench;
mod derive_action;
mod derive_app_context;
mod derive_into_element;
@@ -189,6 +190,12 @@ pub fn test(args: TokenStream, function: TokenStream) -> TokenStream {
test::test(args, function)
}
+/// `#[gpui::bench]` annotates a Criterion benchmark that runs with GPUI support.
+#[proc_macro_attribute]
+pub fn bench(args: TokenStream, function: TokenStream) -> TokenStream {
+ bench::bench(args, function)
+}
+
/// A variant of `#[gpui::test]` that supports property-based testing.
///
/// A property test, much like a standard GPUI randomized test, allows testing