Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui_platform: Extend benchmarks and add a two-revision comparison script (#66316)
Anthony Eid26abd1c95908
diff --git a/crates/gpui/src/app/bench_context.rs b/crates/gpui/src/app/bench_context.rsindex a577a0bc407..5b433800d37 100644--- a/crates/gpui/src/app/bench_context.rs+++ b/crates/gpui/src/app/bench_context.rs@@ -15,9 +15,9 @@ use hdrhistogram::Histogram;use crate::{AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, Bounds, Context, Empty,- Entity, EntityId, Focusable, ForegroundExecutor, Global, Platform, PlatformHeadlessRenderer,- PlatformTextSystem, Render, Reservation, Task, TestPlatform, ThreadedDispatcher, VisualContext,- Window, WindowBounds, WindowHandle, WindowOptions,+ Entity, EntityId, Focusable, ForegroundExecutor, Global, Pixels, Platform,+ PlatformHeadlessRenderer, PlatformTextSystem, Render, Reservation, Size, Task, TestPlatform,+ ThreadedDispatcher, VisualContext, Window, WindowBounds, WindowHandle, WindowOptions,app::GpuiBorrow,profiler::{self, FrameEvent, FrameTimingCollector,@@ -1207,6 +1207,25 @@ impl<'a, 'measurement> BenchWindowContext<'a, 'measurement> {.update_window(self.window, |_, window, cx| update(window, cx)).expect("benchmark window was unexpectedly closed")}++ /// Resizes the window's content area as the platform does when the user drags its+ /// edge, through the window's resize callback. The next frame redraws at the new size.+ ///+ /// Must not be called from inside [`Self::update`]: the callback updates the window.+ pub fn simulate_resize(&mut self, size: Size<Pixels>) {+ let mut platform_window = {+ let mut app = self.cx.app.borrow_mut();+ app.windows+ .get_mut(self.window.window_id())+ .and_then(|window| window.as_deref_mut())+ .expect("benchmark window was unexpectedly closed")+ .platform_window+ .as_test()+ .expect("benchmark platform window")+ .clone()+ };+ platform_window.simulate_resize(size);+ }}impl AppContext for BenchWindowContext<'_, '_> {diff --git a/crates/gpui/src/randomized_element_tree.rs b/crates/gpui/src/randomized_element_tree.rsindex b483cb7efa8..01b9f204abf 100644--- a/crates/gpui/src/randomized_element_tree.rs+++ b/crates/gpui/src/randomized_element_tree.rs@@ -1,8 +1,8 @@//! A seeded, mutable element tree for benchmarks and tests of GPUI rendering.use crate::{- AnyElement, AppContext as _, Context, ElementId, Entity, Hsla, InteractiveElement, IntoElement,- ParentElement, Render, StatefulInteractiveElement, Styled, Window, div, px,- util::FluentBuilder,+ AnimationExt as _, AnyElement, AppContext as _, Context, ElementId, Entity, Hsla,+ InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled,+ Window, div, px, util::FluentBuilder,};use collections::{HashMap, HashSet};use rand::{Rng as _, SeedableRng as _, rngs::StdRng};@@ -62,6 +62,9 @@ pub struct RandomizedElementTreeConfig {topology: RandomizedElementTreeTopology,entity_density: f64,handler_density: f64,+ animation_density: f64,+ cached_views: bool,+ hover_styles: bool,}impl RandomizedElementTreeConfig {@@ -73,9 +76,32 @@ impl RandomizedElementTreeConfig {topology: RandomizedElementTreeTopology::from_seed(seed),entity_density: 0.0,handler_density: 0.0,+ animation_density: 0.0,+ cached_views: false,+ hover_styles: false,}}+ /// Use definite-size cached entity boundaries in this separate workload variant.+ pub fn with_cached_views(mut self, cached: bool) -> Self {+ self.cached_views = cached;+ self+ }++ /// Sets the probability that each entity-backed element shows a looping animation, like+ /// a spinner, so its entity re-renders on every frame while the window is open.+ pub fn with_animation_density(mut self, density: f64) -> Self {+ self.animation_density = normalized_density(density);+ self+ }++ /// Gives every element a hover style and a group-hover style keyed to the tree's root.+ /// Off by default, so workloads that never move the pointer don't pay for them.+ pub fn with_hover_styles(mut self, hover_styles: bool) -> Self {+ self.hover_styles = hover_styles;+ self+ }+/// Selects the initial tree topology independently of the RNG seed.pub fn with_topology(mut self, topology: RandomizedElementTreeTopology) -> Self {self.topology = topology;@@ -192,15 +218,49 @@ fn sample_range(range: &RangeInclusive<f64>, rng: &mut StdRng) -> f64 {}/// Work performed while converting randomized entities and elements into an element tree.+///+/// Recorded only in tests: benchmarks must not pay for bookkeeping, and the rendered-ID+/// history would otherwise grow for as long as a benchmark draws without resetting it.#[derive(Clone, Debug, Default, Eq, PartialEq)]pub struct RandomizedElementTreeWorkCounters {+ #[cfg(test)]root_render_count: usize,+ #[cfg(test)]entity_render_count: usize,+ #[cfg(test)]element_render_count: usize,+ #[cfg(test)]handler_registration_count: usize,+ #[cfg(test)]rendered_entity_ids: Vec<u64>,}+impl RandomizedElementTreeWorkCounters {+ fn record_root_render(&mut self) {+ #[cfg(test)]+ {+ self.root_render_count += 1;+ }+ }++ fn record_entity_render(&mut self, _element_id: u64) {+ #[cfg(test)]+ {+ self.entity_render_count += 1;+ self.rendered_entity_ids.push(_element_id);+ }+ }++ fn record_element_render(&mut self, _handler_count: usize) {+ #[cfg(test)]+ {+ self.element_render_count += 1;+ self.handler_registration_count += _handler_count;+ }+ }+}++#[cfg(test)]impl RandomizedElementTreeWorkCounters {/// Returns how many times the persistent root's `Render` implementation ran.pub fn root_render_count(&self) -> usize {@@ -242,6 +302,8 @@ pub struct RandomizedElementTreeSnapshot {root: RandomizedElementStyle,children: Vec<RandomizedElementNode>,next_element_id: u64,+ cached_views: bool,+ hover_styles: bool,paths_by_element_id: HashMap<u64, Vec<usize>>,}@@ -480,6 +542,7 @@ pub struct RecoloredChildren {pub struct RandomizedElementTree {snapshot: Rc<RefCell<RandomizedElementTreeSnapshot>>,entities: Rc<RefCell<RandomizedElementEntities>>,+ scroll_handles: Rc<RefCell<HashMap<u64, crate::ScrollHandle>>>,work_counters: Rc<RefCell<RandomizedElementTreeWorkCounters>>,config: RandomizedElementTreeConfig,rng: StdRng,@@ -518,12 +581,7 @@ impl RandomizedElementTree {}}};- let node = RandomizedElementNode::random(- element_index as u64,- config.entity_density,- config.handler_density,- &mut rng,- );+ let node = RandomizedElementNode::random(element_index as u64, &config, &mut rng);let (_, inserted_path) = insert_node(&mut children, &mut parent_path, node);deepest_path = inserted_path;}@@ -532,6 +590,8 @@ impl RandomizedElementTree {root: RandomizedElementStyle::random_root(&mut rng),children,next_element_id: config.element_count as u64,+ cached_views: config.cached_views,+ hover_styles: config.hover_styles,paths_by_element_id: HashMap::default(),};snapshot.rebuild_element_paths();@@ -539,6 +599,7 @@ impl RandomizedElementTree {Self {snapshot: Rc::new(RefCell::new(snapshot)),entities: Rc::new(RefCell::new(HashMap::default())),+ scroll_handles: Rc::default(),work_counters: Rc::new(RefCell::new(RandomizedElementTreeWorkCounters::default())),config,rng,@@ -551,6 +612,7 @@ impl RandomizedElementTree {config: RandomizedElementTreeConfig::new(0, snapshot.descendant_count()),snapshot: Rc::new(RefCell::new(snapshot)),entities: Rc::new(RefCell::new(HashMap::default())),+ scroll_handles: Rc::default(),work_counters: Rc::new(RefCell::new(RandomizedElementTreeWorkCounters::default())),rng: StdRng::seed_from_u64(0),}@@ -572,11 +634,13 @@ impl RandomizedElementTree {}/// Clears render work accumulated since construction or the previous reset.+ #[cfg(test)]pub fn reset_work_counters(&mut self) {self.work_counters.borrow_mut().reset();}/// Returns work accumulated since construction or the previous reset.+ #[cfg(test)]pub fn work_counters(&self) -> RandomizedElementTreeWorkCounters {self.work_counters.borrow().clone()}@@ -617,6 +681,39 @@ impl RandomizedElementTree {applied.mutation}+ /// Picks a seeded random element, at any depth, or `None` if the tree is empty.+ pub fn random_element_id(&mut self) -> Option<u64> {+ let snapshot = self.snapshot.borrow();+ let path = random_node_path(&snapshot.children, &mut self.rng)?;+ node_at_path(&snapshot.children, &path).map(|node| node.id)+ }++ /// Alternates an element's background between two colors without changing the tree's+ /// shape, notifying its nearest persistent entity boundary. Returns `false` if the+ /// element is no longer in the tree.+ pub fn alternate_element_color(&mut self, element_id: u64, cx: &mut Context<Self>) -> bool {+ let owner = {+ let mut snapshot = self.snapshot.borrow_mut();+ let Some(path) = snapshot.paths_by_element_id.get(&element_id).cloned() else {+ return false;+ };+ let owner = nearest_entity_id(&snapshot.children, &path);+ let Some(node) = node_at_path_mut(&mut snapshot.children, &path) else {+ return false;+ };+ let first = crate::hsla(0., 1., 0.5, 1.);+ let second = crate::hsla(0.5, 1., 0.5, 1.);+ node.style.background = if node.style.background == first {+ second+ } else {+ first+ };+ owner+ };+ self.notify_owner(owner, cx);+ true+ }+/// Generates and inserts an element below a seeded random parent.////// This does not synchronize or notify persistent child entities. Entity-aware callers should@@ -716,12 +813,7 @@ impl RandomizedElementTree {let mut parent_path = random_parent_path(&snapshot.children, &mut self.rng);let parent_id = node_at_path(&snapshot.children, &parent_path).map(|node| node.id);let owner_entity_id = nearest_entity_id(&snapshot.children, &parent_path);- let node = RandomizedElementNode::random(- element_id,- self.config.entity_density,- self.config.handler_density,- &mut self.rng,- );+ let node = RandomizedElementNode::random(element_id, &self.config, &mut self.rng);let (index, _) = insert_node(&mut snapshot.children, &mut parent_path, node);snapshot.rebuild_element_paths();@@ -758,6 +850,13 @@ impl RandomizedElementTree {let removed_element_count = removed.element_count();let element_id = removed.id;snapshot.rebuild_element_paths();+ let mut scroll_handles = self.scroll_handles.borrow_mut();+ let mut removed_nodes = vec![&removed];+ while let Some(node) = removed_nodes.pop() {+ scroll_handles.remove(&node.id);+ removed_nodes.extend(node.children.iter());+ }+ drop(scroll_handles);Some(AppliedRandomizedElementTreeMutation {mutation: RandomizedElementTreeMutation::Removed {element_id,@@ -783,7 +882,7 @@ impl RandomizedElementTree {locality: ChangeLocality,cx: &mut Context<Self>,) -> RecoloredChildren {- let owners = {+ let (owners, recolored) = {let mut snapshot = self.snapshot.borrow_mut();let mut paths = node_paths(&snapshot.children);let count = count.min(paths.len());@@ -826,10 +925,9 @@ impl RandomizedElementTree {node.style.background = random_color(&mut self.rng);}}- owners+ (owners, count)};let notified = owners.len();- let recolored = count.min(self.snapshot.borrow().descendant_count());for owner in owners {self.notify_owner(owner, cx);}@@ -848,6 +946,8 @@ impl RandomizedElementTree {drop(snapshot);return self.insert_child_internal();};+ // Notifying a view also re-renders its ancestors, so this reaches the view that+ // passes a cached entity's size to `.cached(style)` too.let owner_entity_id = nearest_entity_id(&snapshot.children, &path);let Some(node) = node_at_path_mut(&mut snapshot.children, &path) else {drop(snapshot);@@ -869,8 +969,17 @@ impl RandomizedElementTree {RandomizedElementTreeMutation::ChildBorder { element_id }}RandomizedChildMutation::Bounds => {- node.style.width = self.rng.random_range(36.0..220.0);- node.style.height = self.rng.random_range(28.0..180.0);+ // Occasionally collapse an axis to exercise empty bounds.+ node.style.width = if self.rng.random_bool(0.02) {+ 0.0+ } else {+ self.rng.random_range(36.0..220.0)+ };+ node.style.height = if self.rng.random_bool(0.02) {+ 0.0+ } else {+ self.rng.random_range(28.0..180.0)+ };RandomizedElementTreeMutation::ChildBounds { element_id }}RandomizedChildMutation::Clipping => {@@ -974,18 +1083,11 @@ impl RandomizedElementTree {element_id,snapshot: self.snapshot.clone(),entities: weak_entities.clone(),+ scroll_handles: self.scroll_handles.clone(),work_counters: self.work_counters.clone(),});self.entities.borrow_mut().insert(element_id, entity);}-- let entity_count = self.entities.borrow().len();- let mut work_counters = self.work_counters.borrow_mut();- let additional_capacity =- entity_count.saturating_sub(work_counters.rendered_entity_ids.len());- work_counters- .rendered_entity_ids- .reserve(additional_capacity);}fn notify_owner(&self, owner_entity_id: Option<u64>, cx: &mut Context<Self>) {@@ -1005,16 +1107,22 @@ impl Render for RandomizedElementTree {let root = &snapshot.root;let entities = self.entities.borrow();let mut work_counters = self.work_counters.borrow_mut();- work_counters.root_render_count += 1;+ work_counters.record_root_render();div().flex()+ .when(snapshot.hover_styles, |element| {+ element.group("randomized-tree-root")+ }).when(root.vertical, |element| element.flex_col()).when(root.wrap, |element| element.flex_wrap()).gap(px(root.gap)).p(px(root.padding)).w(px(root.width)).h(px(root.height))+ // Shrinks with a window smaller than the root, so resizing it changes layout.+ .max_w_full()+ .max_h_full().bg(root.background).border(px(root.border_width)).border_color(root.border_color)@@ -1022,12 +1130,16 @@ impl Render for RandomizedElementTree {.opacity(root.opacity).when(root.clipped, |element| element.overflow_hidden()).when(!root.visible, |element| element.invisible())- .children(- snapshot- .children- .iter()- .map(|node| render_node(node, &entities, &mut work_counters)),- )+ .children(snapshot.children.iter().map(|node| {+ render_node(+ node,+ &entities,+ &self.scroll_handles,+ &mut work_counters,+ snapshot.cached_views,+ snapshot.hover_styles,+ )+ }))}}@@ -1037,6 +1149,7 @@ struct RandomizedElementEntity {element_id: u64,snapshot: Rc<RefCell<RandomizedElementTreeSnapshot>>,entities: Weak<RefCell<RandomizedElementEntities>>,+ scroll_handles: Rc<RefCell<HashMap<u64, crate::ScrollHandle>>>,work_counters: Rc<RefCell<RandomizedElementTreeWorkCounters>>,}@@ -1046,12 +1159,20 @@ impl Render for RandomizedElementEntity {let entities = self.entities.upgrade();let entities = entities.as_ref().map(|entities| entities.borrow());let mut work_counters = self.work_counters.borrow_mut();- work_counters.entity_render_count += 1;- work_counters.rendered_entity_ids.push(self.element_id);+ work_counters.record_entity_render(self.element_id);snapshot.node(self.element_id)- .map(|node| render_node_body(node, entities.as_deref(), &mut work_counters))+ .map(|node| {+ render_node_body(+ node,+ entities.as_deref(),+ &self.scroll_handles,+ &mut work_counters,+ snapshot.cached_views,+ snapshot.hover_styles,+ )+ }).unwrap_or_else(|| div().into_any_element())}}@@ -1082,12 +1203,19 @@ struct RandomizedElementNode {}impl RandomizedElementNode {- fn random(id: u64, entity_density: f64, handler_density: f64, rng: &mut StdRng) -> Self {+ fn random(id: u64, config: &RandomizedElementTreeConfig, rng: &mut StdRng) -> Self {+ let style = RandomizedElementStyle::random_child(rng);+ let is_entity = rng.random_bool(config.entity_density);+ let mut features = RandomizedElementFeatures::random(config.handler_density, rng);+ // Drawn only when enabled, so trees without animations keep the same RNG stream.+ features.animated = is_entity+ && config.animation_density > 0.0+ && rng.random_bool(config.animation_density);Self {id,- style: RandomizedElementStyle::random_child(rng),- is_entity: rng.random_bool(entity_density),- features: RandomizedElementFeatures::random(handler_density, rng),+ style,+ is_entity,+ features,children: Vec::new(),}}@@ -1108,6 +1236,7 @@ struct RandomizedElementFeatures {action_handler: bool,click_handler: bool,key_context: bool,+ animated: bool,}impl RandomizedElementFeatures {@@ -1116,6 +1245,7 @@ impl RandomizedElementFeatures {action_handler: rng.random_bool(handler_density),click_handler: rng.random_bool(handler_density),key_context: rng.random_bool(handler_density),+ animated: false,}}@@ -1199,25 +1329,44 @@ enum RandomizedChildMutation {fn render_node(node: &RandomizedElementNode,entities: &RandomizedElementEntities,+ scroll_handles: &RefCell<HashMap<u64, crate::ScrollHandle>>,work_counters: &mut RandomizedElementTreeWorkCounters,+ cached_views: bool,+ hover_styles: bool,) -> AnyElement {if node.is_entity&& let Some(entity) = entities.get(&node.id){+ if cached_views {+ let mut style = crate::StyleRefinement::default();+ style.size.width = Some(px(node.style.width).into());+ style.size.height = Some(px(node.style.height).into());+ style.flex_shrink = Some(0.0);+ return entity.clone().cached(style).into_any_element();+ }return entity.clone().into_any_element();}- render_node_body(node, Some(entities), work_counters)+ render_node_body(+ node,+ Some(entities),+ scroll_handles,+ work_counters,+ cached_views,+ hover_styles,+ )}#[cfg_attr(feature = "stacker", stacksafe::stacksafe)]fn render_node_body(node: &RandomizedElementNode,entities: Option<&RandomizedElementEntities>,+ scroll_handles: &RefCell<HashMap<u64, crate::ScrollHandle>>,work_counters: &mut RandomizedElementTreeWorkCounters,+ cached_views: bool,+ hover_styles: bool,) -> AnyElement {- work_counters.element_render_count += 1;- work_counters.handler_registration_count += node.features.handler_count();+ work_counters.record_element_render(node.features.handler_count());let style = &node.style;div().id(ElementId::NamedInteger(@@ -1225,6 +1374,7 @@ fn render_node_body(node.id,)).flex()+ .flex_shrink_0().when(style.vertical, |element| element.flex_col()).when(style.wrap, |element| element.flex_wrap()).gap(px(style.gap))@@ -1232,26 +1382,115 @@ fn render_node_body(.w(px(style.width)).h(px(style.height)).bg(style.background)+ .when(hover_styles, |element| {+ element+ .hover(|element| {+ element+ .bg(style.border_color)+ .border(px(style.border_width + 1.0))+ })+ .group_hover("randomized-tree-root", |element| element.opacity(0.65))+ }).border(px(style.border_width)).border_color(style.border_color).rounded(px(style.corner_radius))+ .when(node.id.is_multiple_of(2), |element| {+ element.shadow(vec![+ crate::BoxShadow::new(px(-style.gap), px(style.gap), style.border_color)+ .blur_radius(px(style.corner_radius)),+ ])+ }).opacity(style.opacity).when(style.clipped, |element| element.overflow_hidden())+ .when(node.id.is_multiple_of(3), |element| {+ let mut handles = scroll_handles.borrow_mut();+ let handle = handles+ .entry(node.id)+ .or_insert_with(crate::ScrollHandle::new);+ element.overflow_scroll().track_scroll(handle)+ }).when(!style.visible, |element| element.invisible()).when(node.features.action_handler, |element| {element.on_action(|_: &RandomizedElementTreeAction, _window, _cx| {})}).when(node.features.click_handler, |element| {- element.on_click(|_event, _window, _cx| {})+ element.cursor_pointer().on_click(|_event, _window, _cx| {})}).when(node.features.key_context, |element| {- element.key_context("RandomizedElementTree")+ element+ .key_context("RandomizedElementTree")+ .tab_index((node.id % 5) as isize)+ .tab_stop(!node.id.is_multiple_of(7))+ })+ .when(node.id.is_multiple_of(5), |element| element.tab_group())+ .when(node.features.animated, |element| {+ element.child(+ div()+ .size(px(10.))+ .flex_shrink_0()+ .rounded_full()+ .bg(style.border_color)+ .with_animation(+ ElementId::NamedInteger("randomized-spinner".into(), node.id),+ crate::Animation::new(std::time::Duration::from_millis(800)).repeat(),+ |element, delta| element.opacity(0.25 + 0.75 * delta),+ ),+ )+ })+ .when(node.id % 4 == 1, |element| {+ element.underline().child("Retained glyphs: abc Ω")+ })+ .child({+ let color = style.border_color;+ let width = style.border_width;+ let bend = style.corner_radius;+ crate::canvas(+ |_, _, _| (),+ move |bounds, (), window, _| {+ for index in 0..6 {+ let mut path = if index % 2 == 0 {+ crate::PathBuilder::fill()+ } else {+ crate::PathBuilder::stroke(px(width + 0.5))+ };+ let origin =+ bounds.origin + crate::point(px(index as f32 * 3.0 - 8.0), px(-4.0));+ path.move_to(origin);+ path.curve_to(+ origin + crate::point(bounds.size.width, bounds.size.height),+ origin + crate::point(px(bend), px(-bend)),+ );+ path.line_to(origin + crate::point(px(-bend), bounds.size.height));+ path.close();+ window.paint_path(+ path.build().expect("generated path must tessellate"),+ color,+ );+ }+ },+ )+ .absolute()+ .size_full()}).children(node.children.iter().map(|child| {if let Some(entities) = entities {- render_node(child, entities, work_counters)+ render_node(+ child,+ entities,+ scroll_handles,+ work_counters,+ cached_views,+ hover_styles,+ )} else {- render_node_body(child, None, work_counters)+ render_node_body(+ child,+ None,+ scroll_handles,+ work_counters,+ cached_views,+ hover_styles,+ )}})).into_any_element()@@ -1429,19 +1668,65 @@ mod tests {#[derive(Debug, PartialEq)]struct SceneSnapshot {quads: Vec<QuadSnapshot>,+ /// Every other primitive kind, formatted without the per-window atlas tile and+ /// path IDs, which differ between two windows drawing the same scene.+ other_primitives: Vec<String>,element_ids: BTreeSet<u64>,}impl SceneSnapshot {fn from_window(window: &Window) -> Self {+ let scene = &window.rendered_frame.scene;+ let other_primitives = scene+ .shadows+ .iter()+ .map(|shadow| format!("{shadow:?}"))+ .chain(+ scene+ .underlines+ .iter()+ .map(|underline| format!("{underline:?}")),+ )+ .chain(scene.paths.iter().map(|path| {+ format!(+ "path {} {:?} {:?} {:?} {:?}",+ path.order, path.bounds, path.content_mask, path.color, path.vertices+ )+ }))+ .chain(scene.monochrome_sprites.iter().map(|sprite| {+ format!(+ "monochrome {} {:?} {:?} {:?} {:?}",+ sprite.order,+ sprite.bounds,+ sprite.content_mask,+ sprite.color,+ sprite.transformation+ )+ }))+ .chain(scene.subpixel_sprites.iter().map(|sprite| {+ format!(+ "subpixel {} {:?} {:?} {:?} {:?}",+ sprite.order,+ sprite.bounds,+ sprite.content_mask,+ sprite.color,+ sprite.transformation+ )+ }))+ .chain(scene.polychrome_sprites.iter().map(|sprite| {+ format!(+ "polychrome {} {:?} {:?} {:?} {}",+ sprite.order,+ sprite.bounds,+ sprite.content_mask,+ sprite.grayscale,+ sprite.opacity+ )+ }))+ .collect();Self {- quads: window- .rendered_frame- .scene- .quads- .iter()- .map(QuadSnapshot::from)- .collect(),+ quads: scene.quads.iter().map(QuadSnapshot::from).collect(),+ other_primitives,element_ids: window.rendered_frame.element_statesdiff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rsindex c2ba13d506a..79b204c6e19 100644--- a/crates/gpui/src/window.rs+++ b/crates/gpui/src/window.rs@@ -3094,6 +3094,13 @@ impl Window {.render_to_image(&self.rendered_frame.scene)}+ /// Borrows the most recently rendered frame's scene, so benchmarks can validate their+ /// output and report batch counts without cloning it.+ #[cfg(feature = "bench-support")]+ pub fn rendered_scene(&self) -> &Scene {+ &self.rendered_frame.scene+ }+/// Returns the quads in the most recently rendered frame's scene, so tests can assert on/// painted output without rasterizing the frame. Quad bounds are in scaled pixels and are/// not clipped; each quad carries the content mask it will be clipped to when drawn. Quadsdiff --git a/crates/gpui_platform/Cargo.toml b/crates/gpui_platform/Cargo.tomlindex 4520063e897..d0b6bcaf742 100644--- a/crates/gpui_platform/Cargo.toml+++ b/crates/gpui_platform/Cargo.toml@@ -47,6 +47,11 @@ name = "randomized_element_tree"harness = falserequired-features = ["bench-support"]+[[bench]]+name = "primitives"+harness = false+required-features = ["bench-support"]+[dependencies]anyhow.workspace = truegpui.workspace = truediff --git a/crates/gpui_platform/benches/inspector_render.rs b/crates/gpui_platform/benches/inspector_render.rsindex 811155ffb4a..958916e66d6 100644--- a/crates/gpui_platform/benches/inspector_render.rs+++ b/crates/gpui_platform/benches/inspector_render.rs@@ -1,9 +1,9 @@-use std::{cell::Cell, fmt, rc::Rc, time::Duration};+use std::{fmt, time::Duration};use gpui::{- BenchAppContext, Bounds, Context, InteractiveElement as _, IntoElement, ParentElement as _,- Pixels, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div,- prelude::FluentBuilder as _, px, rgb, size,+ BenchAppContext, Context, InteractiveElement as _, IntoElement, ParentElement as _, Render,+ SharedString, StatefulInteractiveElement as _, Styled as _, Window, div,+ prelude::FluentBuilder as _, px, rgb,};const COLUMN_COUNT: usize = 100;@@ -11,23 +11,6 @@ const NODE_SIZE: f32 = 6.0;const ROW_HEIGHT: f32 = 24.0;const PANEL_WIDTH: f32 = 320.0;-#[derive(Default)]-struct RenderWork {- rendered_frames: Cell<usize>,- prepainted_children: Cell<usize>,- invalid_children: Cell<usize>,-}--impl RenderWork {- fn record_children(&self, bounds: &[Bounds<Pixels>], valid: impl Fn(&Bounds<Pixels>) -> bool) {- self.prepainted_children- .set(self.prepainted_children.get() + bounds.len());- self.invalid_children.set(- self.invalid_children.get() + bounds.iter().filter(|bounds| !valid(bounds)).count(),- );- }-}-struct ClosedInspectorInput {scale: usize,unit: &'static str,@@ -82,14 +65,12 @@ fn closed_inspector_inputs(fps = 120)]fn bare_grid(input: &ClosedInspectorInput, cx: &mut BenchAppContext) {- assert_eq!(input.scale % COLUMN_COUNT, 0);measure_closed_inspector(input,cx,- |work| BareGrid {+ || BareGrid {node_count: input.scale,alternate: false,- work,},|grid| grid.alternate = !grid.alternate,);@@ -105,7 +86,7 @@ fn panel(input: &ClosedInspectorInput, cx: &mut BenchAppContext) {measure_closed_inspector(input,cx,- |work| Panel::new(input.scale, work),+ || Panel::new(input.scale),|panel| panel.selected_row = (panel.selected_row + 1) % panel.labels.len(),);}@@ -113,108 +94,76 @@ fn panel(input: &ClosedInspectorInput, cx: &mut BenchAppContext) {fn measure_closed_inspector<V: Render + 'static>(input: &ClosedInspectorInput,cx: &mut BenchAppContext,- build_view: impl FnOnce(Rc<RenderWork>) -> V,+ build_view: impl FnOnce() -> V,mut update_view: impl FnMut(&mut V),) {assert!(!cfg!(debug_assertions), "use --profile release-fast");- let expected_children = input.scale;- let work = Rc::new(RenderWork::default());let mut window = cx.add_empty_window();- let view = window.update(|window, cx| {- assert!(!window.is_inspector_picking(cx));- window.replace_root(cx, |_, _| build_view(work.clone()))- });+ let view = window.update(|window, cx| window.replace_root(cx, |_, _| build_view()));cx.run_until_idle();- for _ in 0..input.open_close_cycles {- for open in [true, false] {+ // Inputs with open/close cycles or another inspected window exist only with the+ // `inspector` feature.+ #[cfg(feature = "inspector")]+ let _other_window = {+ for _ in 0..input.open_close_cycles * 2 {window.update(|window, cx| {- #[cfg(feature = "inspector")]window.toggle_inspector(cx);- assert_eq!(window.is_inspector_picking(cx), open);window.refresh();});cx.run_until_idle();}- }- let mut other_window = input.other_window_inspected.then(|| {- let mut window = cx.add_empty_window();- window.update(|window, cx| {- #[cfg(feature = "inspector")]- window.toggle_inspector(cx);- assert!(window.is_inspector_picking(cx));+ // Setup checks, before timing: a toggle that stopped working would otherwise+ // silently measure a different inspector state than the case name says.+ assert!(+ !window.update(|window, cx| window.is_inspector_picking(cx)),+ "the measured window's inspector must be closed"+ );+ // Keep the other window alive, with its inspector open, while this one is measured.+ let other_window = input.other_window_inspected.then(|| {+ let mut other_window = cx.add_empty_window();+ other_window.update(|window, cx| window.toggle_inspector(cx));+ assert!(+ other_window.update(|window, cx| window.is_inspector_picking(cx)),+ "the other window's inspector must be open"+ );+ other_window});- window- });+ // Opening the other window activated it, and inactive windows draw at a throttled+ // rate, so give activation back to the measured window.+ window.update(|window, _| window.activate_window());+ cx.run_until_idle();+ assert!(+ window.update(|window, _| window.is_window_active()),+ "the measured window must be active"+ );+ other_window+ };+ cx.run_until_idle();+ window.update(|window, _| window.refresh());cx.run_until_idle();- let other_frames_before = other_window.as_mut().map(|window| {- window.update(|window, _| {- window- .frame_duration_snapshot()- .draw_duration_histogram- .len()- })- });- assert!(work.rendered_frames.get() > 0);- assert_eq!(- work.prepainted_children.get(),- work.rendered_frames.get() * expected_children- );- assert_eq!(work.invalid_children.get(), 0);- work.rendered_frames.set(0);- work.prepainted_children.set(0);- let frames_before = window.update(|window, _| window.frame_duration_snapshot());- let mut updated_frames = 0;cx.bench_renderer(view, |view, _, cx| {update_view(view);- updated_frames += 1;cx.notify();});- let frames_after = window.update(|window, cx| {- assert!(!window.is_inspector_picking(cx));- window.frame_duration_snapshot()- });-- let other_frames_after = other_window.as_mut().map(|window| {- window.update(|window, cx| {- assert!(window.is_inspector_picking(cx));- window- .frame_duration_snapshot()- .draw_duration_histogram- .len()- })- });- assert_eq!(other_frames_after, other_frames_before);- assert!(updated_frames > 0);- assert_eq!(work.rendered_frames.get(), updated_frames);- assert_eq!(- work.prepainted_children.get(),- updated_frames * expected_children- );- assert_eq!(work.invalid_children.get(), 0);- assert_eq!(- frames_after.draw_duration_histogram.len() - frames_before.draw_duration_histogram.len(),- updated_frames as u64- );- assert_eq!(- frames_after.dirty_to_present_histogram.len()- - frames_before.dirty_to_present_histogram.len(),- updated_frames as u64- );+ if std::env::var("GPUI_BENCH_SCENE_STATS").as_deref() == Ok("1") {+ window.update(|window, _| {+ eprintln!(+ "scene stats inspector/{input}: batches={}",+ window.rendered_scene().batches().count(),+ );+ });+ }}struct BareGrid {node_count: usize,alternate: bool,- work: Rc<RenderWork>,}impl Render for BareGrid {fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {- self.work- .rendered_frames- .set(self.work.rendered_frames.get() + 1);let background = rgb(if self.alternate { 0x334455 } else { 0x445566 });div()@@ -223,13 +172,7 @@ impl Render for BareGrid {.flex_col().size(px(COLUMN_COUNT as f32 * NODE_SIZE)).children((0..self.node_count / COLUMN_COUNT).map(|row_index| {- let work = self.work.clone();div()- .on_children_prepainted(move |bounds, _, _| {- work.record_children(&bounds, |bounds| {- bounds.size == size(px(NODE_SIZE), px(NODE_SIZE))- });- }).id(("row", row_index)).flex().h(px(NODE_SIZE))@@ -253,11 +196,10 @@ struct Panel {labels: Vec<SharedString>,counts: Vec<SharedString>,selected_row: usize,- work: Rc<RenderWork>,}impl Panel {- fn new(row_count: usize, work: Rc<RenderWork>) -> Self {+ fn new(row_count: usize) -> Self {Panel {labels: (0..row_count).map(|index| {@@ -268,23 +210,15 @@ impl Panel {.map(|index| SharedString::from(((index * 7) % 100).to_string())).collect(),selected_row: 0,- work,}}}impl Render for Panel {fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {- self.work- .rendered_frames- .set(self.work.rendered_frames.get() + 1);- let work = self.work.clone();let selected_row = self.selected_row;div()- .on_children_prepainted(move |bounds, _, _| {- work.record_children(&bounds, |bounds| bounds.size.height == px(ROW_HEIGHT));- }).id("panel").flex().flex_col()diff --git a/crates/gpui_platform/benches/primitives.rs b/crates/gpui_platform/benches/primitives.rsnew file mode 100644index 00000000000..4b19618675f--- /dev/null+++ b/crates/gpui_platform/benches/primitives.rs@@ -0,0 +1,414 @@+//! Painting many primitives: draw-order assignment (`BoundsTree`), `Scene::finish`+//! sorting and batching, and, through a window, everything from paint to GPU submission.+//!+//! The `random` cases are the general workload: seeded rectangles of every size,+//! scattered and overlapping, painted as a mix of quads, shadows, underlines, filled paths+//! and text. `SEED` and `ITERATIONS` choose the seeds as for `#[gpui::test]`. The fixed+//! patterns isolate the geometry that decides an ordering structure's best and worst+//! cases, such as many primitives overlapping one another (`overlap`, `nested`) or sharing+//! one axis (`stripes`), so a change in `random` can be traced to the shape that caused it.++use std::{fmt, rc::Rc, time::Duration};++use gpui::{+ App, AtlasTextureId, AtlasTextureKind, AtlasTile, Background, BenchAppContext, Bounds,+ BoxShadow, Context, Corners, DevicePixels, Hsla, IntoElement, Path, PathBuilder, Pixels,+ Render, Scene, SharedString, Styled, TextAlign, TextRun, TileId, TransformationMatrix,+ UnderlineStyle, Window, canvas, fill, hsla, point,+ private::rand::{Rng as _, SeedableRng as _, rngs::StdRng},+ px, size,+};++#[derive(Clone, Copy)]+enum Pattern {+ Grid,+ Stripes,+ Overlap,+ Nested,+ Clusters,+ Overlay,+ Random { seed: u64 },+}++struct Case {+ pattern: Pattern,+ count: usize,+}++impl fmt::Display for Case {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ let name = match self.pattern {+ Pattern::Grid => "grid",+ Pattern::Stripes => "stripes",+ Pattern::Overlap => "overlap",+ Pattern::Nested => "nested",+ Pattern::Clusters => "clusters",+ Pattern::Overlay => "overlay",+ Pattern::Random { seed } => {+ return write!(formatter, "random-{}-seed-{seed}", self.count);+ }+ };+ write!(formatter, "{name}-{}", self.count)+ }+}++fn cases() -> Vec<Case> {+ let (seeds, _) = gpui::calculate_seeds(2, &[]);+ let seeds = seeds.collect::<Vec<_>>();+ [256, 1_024, 4_096]+ .into_iter()+ .flat_map(|count| {+ seeds+ .iter()+ .map(|&seed| Pattern::Random { seed })+ .chain([+ Pattern::Grid,+ Pattern::Stripes,+ Pattern::Overlap,+ Pattern::Nested,+ Pattern::Clusters,+ Pattern::Overlay,+ ])+ .map(move |pattern| Case { pattern, count })+ .collect::<Vec<_>>()+ })+ .collect()+}++#[derive(Clone)]+enum Kind {+ Quad,+ Shadow,+ Underline,+ /// Tessellated before timing: path tessellation is measured by the tree benchmarks,+ /// and would otherwise dominate what these cases are for.+ Path(Path<Pixels>),+ Text(SharedString),+}++#[derive(Clone)]+struct Rectangle {+ bounds: Bounds<Pixels>,+ background: Background,+ color: Hsla,+ kind: Kind,+}++fn random_rectangles(seed: u64, count: usize, extent: f32) -> Rc<[Rectangle]> {+ let mut rng = StdRng::seed_from_u64(seed);+ // Log-uniform sizes: mostly small primitives, with a long tail of large ones that+ // overlap many others, as in a real window.+ let (smallest, largest) = (2f32.ln(), (extent * 0.6).ln());+ (0..count)+ .map(|_| {+ let width = rng.random_range(smallest..largest).exp();+ let height = rng.random_range(smallest..largest).exp();+ let origin = point(+ px(32. + rng.random_range(0.0..extent - width)),+ px(32. + rng.random_range(0.0..extent - height)),+ );+ let bounds = Bounds::new(origin, size(px(width), px(height)));+ let color = hsla(rng.random_range(0.0..1.0), 0.8, 0.5, 1.);+ let kind = match rng.random_range(0..20) {+ 0..9 => Kind::Quad,+ 9..11 => Kind::Shadow,+ 11..13 => Kind::Underline,+ 13..16 => triangle(bounds).map_or(Kind::Quad, Kind::Path),+ _ => {+ let length = rng.random_range(1..12);+ Kind::Text("Ag3 Wq7 fixture"[..length].to_string().into())+ }+ };+ Rectangle {+ bounds,+ background: color.into(),+ color,+ kind,+ }+ })+ .collect::<Vec<_>>()+ .into()+}++fn triangle(bounds: Bounds<Pixels>) -> Option<Path<Pixels>> {+ let mut path = PathBuilder::fill();+ path.move_to(bounds.origin);+ path.line_to(bounds.top_right());+ path.line_to(bounds.bottom_left() + point(bounds.size.width / 2., px(0.)));+ path.close();+ path.build().ok()+}++fn rectangles(case: &Case, extent: f32) -> Rc<[Rectangle]> {+ if let Pattern::Random { seed } = case.pattern {+ return random_rectangles(seed, case.count, extent);+ }+ let columns = (case.count as f32).sqrt().ceil() as usize;+ let cell = extent / columns as f32;+ let stripe_count = (extent / 4.).floor() as usize;+ (0..case.count)+ .map(|index| {+ let grid_origin = point(+ px(32. + (index % columns) as f32 * cell),+ px(32. + (index / columns) as f32 * cell),+ );+ let bounds = match case.pattern {+ Pattern::Grid => Bounds::new(grid_origin, size(px(cell * 0.4), px(cell * 0.4))),+ Pattern::Stripes => Bounds::new(+ point(px(32.), px(32. + (index % stripe_count) as f32 * 4.)),+ size(px(extent), px(2.)),+ ),+ Pattern::Overlap => {+ Bounds::new(point(px(32.), px(32.)), size(px(extent), px(extent)))+ }+ Pattern::Nested => {+ let inset = extent * 0.3 * index as f32 / case.count as f32;+ Bounds::new(+ point(px(32. + inset), px(32. + inset)),+ size(px(extent - 2. * inset), px(extent - 2. * inset)),+ )+ }+ Pattern::Clusters => {+ let origin = 32. + (index % 2) as f32 * extent * 0.55;+ Bounds::new(+ point(px(origin), px(origin)),+ size(px(extent * 0.4), px(extent * 0.4)),+ )+ }+ Pattern::Overlay if index % 64 == 0 => {+ Bounds::new(point(px(32.), px(32.)), size(px(extent), px(extent)))+ }+ Pattern::Overlay | Pattern::Random { .. } => {+ Bounds::new(grid_origin, size(px(cell * 0.4), px(cell * 0.4)))+ }+ };+ let color = hsla(index as f32 / case.count as f32, 1., 0.5, 1.);+ Rectangle {+ bounds,+ background: color.into(),+ color,+ kind: Kind::Quad,+ }+ })+ .collect::<Vec<_>>()+ .into()+}++struct OrderingView {+ rectangles: Rc<[Rectangle]>,+}++impl Render for OrderingView {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let rectangles = self.rectangles.clone();+ canvas(+ |_, _, _| {},+ move |_, _, window, cx| {+ for rectangle in rectangles.iter() {+ paint(rectangle, window, cx);+ }+ },+ )+ .size_full()+ }+}++fn paint(rectangle: &Rectangle, window: &mut Window, cx: &mut App) {+ match &rectangle.kind {+ Kind::Quad => window.paint_quad(fill(rectangle.bounds, rectangle.background)),+ Kind::Shadow => window.paint_drop_shadows(+ rectangle.bounds,+ Corners::all(px(4.)),+ &[BoxShadow {+ color: rectangle.color,+ offset: point(px(0.), px(2.)),+ blur_radius: px(6.),+ spread_radius: px(0.),+ inset: false,+ }],+ ),+ Kind::Underline => window.paint_underline(+ rectangle.bounds.origin,+ rectangle.bounds.size.width,+ &UnderlineStyle {+ thickness: rectangle.bounds.size.height.min(px(4.)),+ color: Some(rectangle.color),+ wavy: false,+ },+ ),+ Kind::Path(path) => window.paint_path(path.clone(), rectangle.color),+ // Shaped every frame, as the text element does; the line layout cache makes+ // repeated shaping a lookup.+ Kind::Text(text) => {+ let font_size = rectangle.bounds.size.height.clamp(px(8.), px(32.));+ let run = TextRun {+ len: text.len(),+ font: window.text_style().font(),+ color: rectangle.color,+ background_color: None,+ underline: None,+ strikethrough: None,+ };+ let line = window+ .text_system()+ .shape_line(text.clone(), font_size, &[run], None);+ if let Err(error) = line.paint(+ rectangle.bounds.origin,+ font_size,+ TextAlign::Left,+ None,+ window,+ cx,+ ) {+ eprintln!("failed to paint text: {error}");+ }+ }+ }+}++/// Stands in for one glyph's atlas tile. Spread over a few textures, as glyphs of+/// different sizes and fonts are, so batching by texture is exercised.+fn glyph_tile(index: usize) -> AtlasTile {+ AtlasTile {+ texture_id: AtlasTextureId {+ index: (index % 3) as u32,+ kind: AtlasTextureKind::Monochrome,+ },+ tile_id: TileId(index as u32),+ padding: 0,+ bounds: Bounds::new(+ point(DevicePixels(0), DevicePixels(0)),+ size(DevicePixels(16), DevicePixels(16)),+ ),+ }+}++fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) {+ scene.clear();+ let content_mask = gpui::ContentMask {+ bounds: Bounds::new(point(px(0.), px(0.)), size(px(1_024.), px(1_024.))).scale(1.),+ };+ for (index, rectangle) in rectangles.iter().enumerate() {+ let bounds = rectangle.bounds.scale(1.);+ match &rectangle.kind {+ Kind::Quad => scene.insert_primitive(gpui::Quad {+ order: 0,+ border_style: Default::default(),+ bounds,+ content_mask,+ background: rectangle.background,+ border_color: Default::default(),+ corner_radii: Default::default(),+ border_widths: Default::default(),+ }),+ Kind::Shadow => scene.insert_primitive(gpui::Shadow {+ order: 0,+ blur_radius: gpui::ScaledPixels(6.),+ bounds,+ corner_radii: Corners::all(gpui::ScaledPixels(4.)),+ content_mask,+ color: rectangle.color,+ element_bounds: bounds,+ element_corner_radii: Corners::all(gpui::ScaledPixels(4.)),+ inset: 0,+ pad: 0,+ }),+ Kind::Underline => scene.insert_primitive(gpui::Underline {+ order: 0,+ pad: 0,+ bounds,+ content_mask,+ color: rectangle.color,+ thickness: bounds.size.height.min(gpui::ScaledPixels(4.)),+ wavy: Default::default(),+ }),+ Kind::Path(path) => {+ let mut path = path.scale(1.);+ path.content_mask = content_mask;+ path.color = rectangle.background;+ scene.insert_primitive(path);+ }+ Kind::Text(text) => {+ let glyph_size = bounds.size.height.min(gpui::ScaledPixels(32.));+ for glyph in 0..text.len() {+ let origin = bounds.origin+ + point(glyph_size * (glyph as f32 * 0.6), gpui::ScaledPixels(0.));+ scene.insert_primitive(gpui::MonochromeSprite {+ order: 0,+ pad: 0,+ tile: glyph_tile(index + glyph),+ bounds: Bounds::new(origin, size(glyph_size * 0.6, glyph_size)),+ content_mask,+ color: rectangle.color,+ transformation: TransformationMatrix::unit(),+ });+ }+ }+ }+ }+ scene.finish();+}++fn scene_ordering(criterion: &mut criterion::Criterion<gpui::BenchMeasurement>) {+ let mut group = criterion.benchmark_group("Primitives/scene");+ for case in cases() {+ let mut fixture = None;+ let report = bench_metrics::MetricReport::new();+ group.bench_function(case.to_string(), |bencher| {+ // Criterion invokes this closure only for selected cases. In particular,+ // --list and a paint-only filter must not build every scene.+ let (rectangles, scene) =+ fixture.get_or_insert_with(|| (rectangles(&case, 512.), Scene::default()));+ report.iter(bencher, || {+ build_scene(scene, rectangles);+ std::hint::black_box(&*scene);+ });+ });+ report.print(" ");+ if std::env::var("GPUI_BENCH_SCENE_STATS").as_deref() == Ok("1")+ && let Some((_, scene)) = &fixture+ {+ eprintln!(+ "scene stats Primitives/scene/{case}: batches={}",+ scene.batches().count()+ );+ }+ }+ group.finish();+}++#[gpui::bench(inputs = cases(), input_name = "case", group = "Primitives/paint", fps = 120)]+fn paint_rectangles(case: &Case, cx: &mut BenchAppContext) {+ let mut window = cx.add_empty_window();+ let extent = window.update(|window, _| {+ let viewport = window.viewport_size();+ (viewport.width.as_f32().min(viewport.height.as_f32()) - 64.).min(512.)+ });+ let rectangles = rectangles(case, extent);+ let root =+ window.update(|window, cx| window.replace_root(cx, |_, _| OrderingView { rectangles }));+ cx.run_until_idle();+ window.update(|window, _| window.refresh());+ cx.run_until_idle();+ cx.bench_renderer(root, |_, _, cx| cx.notify());+ window.update(|window, _| {+ if std::env::var("GPUI_BENCH_SCENE_STATS").as_deref() == Ok("1") {+ eprintln!(+ "scene stats Primitives/paint/{case}: batches={}",+ window.rendered_scene().batches().count(),+ );+ }+ });+ window.update(|window, _| window.remove_window());+ cx.run_until_idle();+}++gpui::bench_group!(+ name = benches;+ config = criterion::Criterion::default()+ .warm_up_time(Duration::from_millis(500))+ .measurement_time(Duration::from_secs(1))+ .sample_size(20);+ targets = paint_rectangles, scene_ordering+);+gpui::bench_main!(benches);diff --git a/crates/gpui_platform/benches/randomized_element_tree.rs b/crates/gpui_platform/benches/randomized_element_tree.rsindex 01dbfd4b2c8..551d010b433 100644--- a/crates/gpui_platform/benches/randomized_element_tree.rs+++ b/crates/gpui_platform/benches/randomized_element_tree.rs@@ -1,10 +1,13 @@-//! Frame cost of a seeded element tree under one class of change per frame.+//! Frame cost of seeded element trees, text panels, layout churn and scrolling.//!-//! Each benchmark builds a [`RandomizedElementTree`] before timing, then measures frames in-//! which exactly one thing happens: nothing (a notified root that re-renders an unchanged-//! tree), a leaf's style, a leaf's bounds, the root's layout, one structural change, or a-//! sibling reorder. The same fixture runs on any GPUI revision, so it doubles as the-//! before/after harness for changes to rendering.+//! The `mixed` groups are the general benchmark: each iteration applies a fixed, seeded+//! sequence of many kinds of change to a freshly built [`RandomizedElementTree`], one per+//! frame. The other tree groups each measure frames in which exactly one kind of thing+//! happens, such as nothing (a notified root that re-renders an unchanged tree), one+//! element's style, a leaf's bounds, the root's layout, one structural change, a sibling+//! reorder or a pointer move, to explain where a difference in `mixed` comes from. The+//! same fixture runs on any GPUI revision, so it doubles as the before/after harness for+//! changes to rendering.//!//! Trees come from *families*: bounds on topology, element count and entity density that//! a seeded RNG is drawn against (see [`RandomizedElementTreeBounds`]). Each family is an@@ -15,8 +18,9 @@//! `--bench randomized_element_tree -- 'tree/tall/'`. Each tree is described once, with//! the heap its window holds after the first frame, before it is measured.//!-//! The tree's own work counters are asserted after each measured loop: a faster frame that-//! stopped rendering the changed element is not an improvement.+//! Benchmarks don't check their output; the randomized tree's tests check that what these+//! workloads render is correct, so a faster frame here still needs those tests to pass.+//! The only assertions are one-time setup checks before timing.use std::{cell::RefCell,@@ -24,13 +28,14 @@ use std::{time::{Duration, Instant},};+use gpui::prelude::*;use gpui::{- BenchAppContext, Context, Window,+ BenchAppContext, Context, Entity, Window,private::rand::{Rng as _, SeedableRng as _, rngs::StdRng},randomized_element_tree::{ChangeLocality, RandomizedElementTree, RandomizedElementTreeBounds,RandomizedElementTreeConfig, RandomizedElementTreeMutation,- RandomizedElementTreeMutationKind, RandomizedElementTreeTopology, RecoloredChildren,+ RandomizedElementTreeMutationKind, RandomizedElementTreeTopology,},};@@ -39,6 +44,11 @@ use gpui::{struct TreeFamily {name: &'static str,bounds: RandomizedElementTreeBounds,+ /// Changes per measured iteration of the mixed workload, sized so one iteration of+ /// this family's trees takes at most about half a second on an M-series Mac. Fixed per+ /// family rather than calibrated at run time, so two revisions always measure the+ /// same changes.+ mixed_changes: usize,}impl TreeFamily {@@ -112,12 +122,14 @@ fn families() -> Vec<TreeFamily> {vec![TreeFamily {name: "any",+ mixed_changes: 192,bounds: RandomizedElementTreeBounds::new(32..=TALL_MAX_ELEMENTS).with_entity_density(MIN_ENTITY_DENSITY..=0.5).with_handler_density(handlers.clone()),},TreeFamily {name: "wide",+ mixed_changes: 16,bounds: RandomizedElementTreeBounds::new(128..=2048).with_topologies([RandomizedElementTreeTopology::Wide]).with_entity_density(MIN_ENTITY_DENSITY..=0.25)@@ -125,6 +137,7 @@ fn families() -> Vec<TreeFamily> {},TreeFamily {name: "tall",+ mixed_changes: 512,bounds: RandomizedElementTreeBounds::new(32..=TALL_MAX_ELEMENTS).with_topologies(RandomizedElementTreeTopology::ALL@@ -136,6 +149,7 @@ fn families() -> Vec<TreeFamily> {},TreeFamily {name: "mixed",+ mixed_changes: 192,bounds: RandomizedElementTreeBounds::new(128..=1024).with_topologies([RandomizedElementTreeTopology::Mixed]).with_entity_density(MIN_ENTITY_DENSITY..=0.25)@@ -143,6 +157,7 @@ fn families() -> Vec<TreeFamily> {},TreeFamily {name: "dense-entities",+ mixed_changes: 64,bounds: RandomizedElementTreeBounds::new(128..=1024).with_topologies([RandomizedElementTreeTopology::Wide,@@ -154,23 +169,15 @@ fn families() -> Vec<TreeFamily> {]}-/// Builds the tree, draws it once so layout and the scene are warm, and measures-/// `mutate` once per frame. Returns how many frames were measured, after checking that-/// the frames did render something: a frame that skipped the changed element would be-/// fast and wrong.+/// Builds the tree, draws it twice so layout, the scene and both frame buffers are warm,+/// and measures `mutate` once per frame.fn measure(group: &str,input: &TreeInput,cx: &mut BenchAppContext,mut mutate: impl FnMut(&mut RandomizedElementTree, &mut Context<RandomizedElementTree>),-) -> usize {- measure_in_window(group, input, cx, |tree, _, cx| mutate(tree, cx)).frames-}--/// What a measured loop did: frames measured, and the entity renders the frames showed.-struct Measured {- frames: usize,- entity_renders: usize,+) {+ measure_in_window(group, input, cx, |tree, _, cx| mutate(tree, cx));}fn measure_in_window(@@ -178,7 +185,30 @@ fn measure_in_window(input: &TreeInput,cx: &mut BenchAppContext,mut mutate: impl FnMut(&mut RandomizedElementTree, &mut Window, &mut Context<RandomizedElementTree>),-) -> Measured {+) {+ measure_prepared(+ group,+ input,+ cx,+ |_, _| (),+ |_, tree, window, cx| mutate(tree, window, cx),+ );+}++/// Like [`measure_in_window`], with `prepare` reading the warm window once before timing+/// to build state that every measured frame uses.+fn measure_prepared<State>(+ group: &str,+ input: &TreeInput,+ cx: &mut BenchAppContext,+ prepare: impl FnOnce(&mut RandomizedElementTree, &Window) -> State,+ mut mutate: impl FnMut(+ &mut State,+ &mut RandomizedElementTree,+ &mut Window,+ &mut Context<RandomizedElementTree>,+ ),+) {let config = input.config;let before_window = bench_metrics::allocation_stats();let mut window = cx.add_empty_window();@@ -188,27 +218,13 @@ fn measure_in_window(})});cx.run_until_idle();+ // Warm both frame buffers and their scratch allocations. A short sample can+ // otherwise measure only the cheaper first buffer after mounting the tree.+ window.update(|window, _| window.refresh());+ cx.run_until_idle();describe_once(input, before_window, bench_metrics::allocation_stats());+ let mut state = window.update(|window, cx| tree.update(cx, |tree, _| prepare(tree, window)));- let snapshot = tree.read_with(cx, |tree, _| tree.snapshot());- assert_eq!(snapshot.descendant_count(), config.element_count());- let initial = tree.read_with(cx, |tree, _| tree.work_counters());- assert!(- initial.root_render_count() >= 1,- "the tree must have drawn before timing"- );- assert!(- initial.element_render_count() >= config.element_count(),- "every generated element renders in the first frame"- );-- // Each iteration reads what the previous frame rendered before resetting for its own- // mutation. Frame pacing may coalesce two mutations into one drawn frame, the more- // often the faster the frames, so some observation windows legitimately see no draw;- // a renderer that skipped the changed element would see none in any of them.- let mut frames = 0;- let mut frames_that_rendered = 0;- let mut entity_renders = 0;let mut summary = SeedTotals::default();let mut previous_iteration: Option<(Instant, Option<bench_metrics::AllocationStats>)> = None;cx.bench_renderer(tree, |tree, window, cx| {@@ -225,25 +241,21 @@ fn measure_in_window(}previous_iteration = Some((now, stats));- let previous = tree.work_counters();- entity_renders += previous.entity_render_count();- if previous.root_render_count() + previous.entity_render_count() >= 1- && previous.element_render_count() >= 1- {- frames_that_rendered += 1;- }- tree.reset_work_counters();- mutate(tree, window, cx);- frames += 1;+ mutate(&mut state, tree, window, cx);});- assert!(- frames_that_rendered * 2 >= frames,- "the notified root or entity re-rendered in {frames_that_rendered} of {frames} frames"- );+ window.update(|window, _| report_scene_stats(group, input.family, window));record_for_summary(group, input, summary);- Measured {- frames,- entity_renders,+}++fn report_scene_stats(group: &str, input: &str, window: &Window) {+ if std::env::var("GPUI_BENCH_SCENE_STATS").as_deref() == Ok("1") {+ let scene = window.rendered_scene();+ eprintln!(+ "scene stats {group}/{input}: batches={}, paths={}, surfaces={}",+ scene.batches().count(),+ scene.paths.len(),+ scene.surfaces.len(),+ );}}@@ -343,6 +355,16 @@ fn family_summary(_: &mut criterion::Criterion<gpui::BenchMeasurement>) {"group", "family", "seeds", "time/iter", "allocs/iter");for (group, family, seeds) in summary {+ // A routine call measures from one iteration's start to the next, so a run with a+ // single iteration per call, such as `--test`, has nothing to summarize.+ if seeds.iter().all(|(_, totals)| totals.iterations == 0) {+ eprintln!(+ " {group:<34} {family:<15} {:>5} {:>14}",+ seeds.len(),+ "unavailable"+ );+ continue;+ }let per_iteration = |value: fn(&SeedTotals) -> f64| {geometric_mean(seeds@@ -370,15 +392,7 @@ fn family_summary(_: &mut criterion::Criterion<gpui::BenchMeasurement>) {#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "RandomizedTree/full refresh", fps = 120)]fn full_refresh(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {let input = &family.sample(&mut rng);- let measured = measure_in_window("full refresh", input, cx, |_, window, _| window.refresh());- assert!(measured.frames > 0);- // A full refresh renders every entity; a renderer that replayed them would render none.- if input.config.entity_density() >= 0.25 {- assert!(- measured.entity_renders > 0,- "a full refresh re-renders entities"- );- }+ measure_in_window("full refresh", input, cx, |_, window, _| window.refresh());}/// A frame in which the root is notified but nothing in the tree changed. On a renderer@@ -387,49 +401,51 @@ fn full_refresh(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext)#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "RandomizedTree/unchanged", fps = 120)]fn unchanged(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {let input = &family.sample(&mut rng);- let frames = measure("unchanged", input, cx, |_, cx| cx.notify());- assert!(frames > 0);+ measure("unchanged", input, cx, |_, cx| cx.notify());}-/// One descendant's background color changes each frame: the smallest possible change,-/// confined to one element and, when it has one, its owning entity.-#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "RandomizedTree/leaf style", fps = 120)]-fn leaf_style(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {- let input = &family.sample(&mut rng);- let mut recolored = 0usize;- let frames = measure("leaf style", input, cx, |tree, cx| {- if let RandomizedElementTreeMutation::ChildColor { .. } =- tree.apply_mutation(RandomizedElementTreeMutationKind::ChildColor, cx)- {- recolored += 1;- }- });- assert!(frames > 0);- assert_eq!(- recolored, frames,- "a nonempty tree recolors a child every frame"+/// Alternates the background of one element, chosen at random per seed, at any depth.+/// Recoloring the same element every frame keeps short and long samples measuring the+/// same work.+fn measure_element_style(group: &str, input: &TreeInput, cx: &mut BenchAppContext) {+ measure_prepared(+ group,+ input,+ cx,+ |tree, _| tree.random_element_id(),+ |element_id, tree, _, cx| {+ if let Some(element_id) = element_id {+ tree.alternate_element_color(*element_id, cx);+ }+ },);}+/// One element's background color changes each frame: the smallest possible change,+/// confined to that element and, when it has one, its owning entity.+#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "RandomizedTree/element style", fps = 120)]+fn element_style(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let input = &family.sample(&mut rng);+ measure_element_style("element style", input, cx);+}+/// A descendant's width and height change each frame, so its siblings and ancestors/// re-lay out even where their own content did not change.#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "RandomizedTree/leaf bounds", fps = 120)]fn leaf_bounds(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {let input = &family.sample(&mut rng);- let frames = measure("leaf bounds", input, cx, |tree, cx| {+ measure("leaf bounds", input, cx, |tree, cx| {tree.apply_mutation(RandomizedElementTreeMutationKind::ChildBounds, cx);});- assert!(frames > 0);}/// The root's width and height change each frame: every element's layout is stale.#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "RandomizedTree/root layout", fps = 120)]fn root_layout(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {let input = &family.sample(&mut rng);- let frames = measure("root layout", input, cx, |tree, cx| {+ measure("root layout", input, cx, |tree, cx| {tree.apply_mutation(RandomizedElementTreeMutationKind::RootBounds, cx);});- assert!(frames > 0);}/// One element is inserted or removed per frame, alternating so the tree keeps its size@@ -438,30 +454,15 @@ fn root_layout(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {fn insert_remove(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {let input = &family.sample(&mut rng);let mut insert = true;- let mut inserted = 0usize;- let mut removed = 0usize;- let frames = measure("insert-remove", input, cx, |tree, cx| {+ measure("insert-remove", input, cx, |tree, cx| {let kind = if insert {RandomizedElementTreeMutationKind::Insert} else {RandomizedElementTreeMutationKind::RemoveLeaf};- match tree.apply_mutation(kind, cx) {- RandomizedElementTreeMutation::Inserted { .. } => inserted += 1,- RandomizedElementTreeMutation::Removed {- removed_element_count,- ..- } => {- assert_eq!(removed_element_count, 1, "leaf removal removes one element");- removed += 1;- }- other => panic!("structural mutation produced {other:?}"),- }+ tree.apply_mutation(kind, cx);insert = !insert;});- assert!(frames > 0);- assert_eq!(inserted + removed, frames);- assert!(inserted.abs_diff(removed) <= 1);}/// A descendant moves among its siblings each frame; the set of elements is unchanged@@ -469,22 +470,353 @@ fn insert_remove(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext)#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "RandomizedTree/reorder", fps = 120)]fn reorder(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {let input = &family.sample(&mut rng);- let mut reordered = 0usize;- let frames = measure("reorder", input, cx, |tree, cx| {- if let RandomizedElementTreeMutation::Reordered { .. } =- tree.apply_mutation(RandomizedElementTreeMutationKind::Reorder, cx)- {- reordered += 1;+ // A `Deep` tree has no parent with two children until an insert creates one, so the+ // tree inserts instead; every other shape reorders on every frame.+ measure("reorder", input, cx, |tree, cx| {+ tree.apply_mutation(RandomizedElementTreeMutationKind::Reorder, cx);+ });+}++/// Where the pointer goes in hover workloads: the center of each painted quad's visible+/// part, sorted by position. Hairline quads are skipped: their centers sit on an element's+/// edge, where moving the pointer rarely changes what's hovered.+fn hover_targets(window: &Window) -> Vec<gpui::Point<gpui::Pixels>> {+ let scale_factor = window.scale_factor();+ let mut targets: Vec<gpui::Point<gpui::Pixels>> = Vec::new();+ for quad in &window.rendered_scene().quads {+ let visible = quad.bounds.intersect(&quad.content_mask.bounds);+ let minimum = gpui::ScaledPixels(4. * scale_factor);+ if visible.size.width < minimum || visible.size.height < minimum {+ continue;}+ let center = visible.center();+ let target = gpui::point(+ gpui::px(center.x.0 / scale_factor),+ gpui::px(center.y.0 / scale_factor),+ );+ targets.push(target);+ }+ // Sorted by position so a change to scene order, which is renderer output, doesn't+ // change where the pointer goes.+ targets.sort_by(|a, b| {+ (a.y.as_f32().total_cmp(&b.y.as_f32())).then(a.x.as_f32().total_cmp(&b.x.as_f32()))});- assert!(frames > 0);- // A `Deep` tree has no parent with two children until an insert creates one, so the- // harness inserts instead; every other shape reorders on every frame.- if input.config.topology() != RandomizedElementTreeTopology::Deep {- assert_eq!(reordered, frames);+ targets.dedup();+ targets+}++fn measure_hover(group: &str, input: &TreeInput, cx: &mut BenchAppContext) {+ let mut frame = 0;+ measure_prepared(+ group,+ input,+ cx,+ |_, window| hover_targets(window),+ |targets, _, window, cx| {+ if let Some(position) = targets.get(frame % targets.len().max(1)) {+ window.dispatch_event(+ gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent {+ position: *position,+ modifiers: gpui::Modifiers::default(),+ pressed_button: None,+ }),+ cx,+ );+ }+ frame += 1;+ },+ );+}++/// The pointer moves to a different painted element each frame, as when someone moves the+/// mouse over a window: event dispatch, hit-testing, hover styles turning on and off, and+/// the redraw that follows. A move whose set of hovered elements doesn't change draws+/// nothing, as in a real window; how often that happens depends on the tree's shape. The+/// pointer stays inside the root, so its group-hover styles switch on in setup and stay on.+#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "RandomizedTree/hover", fps = 120)]+fn hover(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let mut input = family.sample(&mut rng);+ input.config = input.config.with_hover_styles(true);+ measure_hover("hover", &input, cx);+}++/// A seeded stream of the changes a real window sees, one per frame: restyles, resizes,+/// structural edits, reorders, scattered recolors, pointer moves, scroll events, focus+/// moves, window resizes and bare notifies, on top of entities that animate every frame.+struct MixedWorkload {+ rng: StdRng,+ /// Draws pointer positions and scroll distances, separately from `rng`, so input+ /// details never shift which changes come next.+ input_rng: StdRng,+ initial_size: usize,+ size: usize,+ root_kinds: Vec<RandomizedElementTreeMutationKind>,+}++impl MixedWorkload {+ fn new(seed: u64, initial_size: usize, cached_views: bool) -> Self {+ use RandomizedElementTreeMutationKind::*;+ let mut root_kinds = vec![RootColor, RootOpacity, RootBorder, RootBounds, RootClipping];+ // Hiding an ancestor of `.cached()` views reuses stale output, and can panic, on+ // `main` today; the cached mix leaves it out until that's fixed.+ if !cached_views {+ root_kinds.push(RootVisibility);+ }+ Self {+ rng: StdRng::seed_from_u64(seed ^ 0x6d69_7865_6421),+ input_rng: StdRng::seed_from_u64(seed ^ 0x696e_7075_7473),+ initial_size,+ size: initial_size,+ root_kinds,+ }+ }++ /// A position over the tree's root, whose largest size is 980 × 760, or just past it.+ /// Drawn from the model's coordinates rather than the rendered scene, so a renderer+ /// change can't move the pointer.+ fn pointer_position(&mut self) -> gpui::Point<gpui::Pixels> {+ gpui::point(+ gpui::px(self.input_rng.random_range(0.0..1000.0)),+ gpui::px(self.input_rng.random_range(0.0..800.0)),+ )+ }++ fn apply(+ &mut self,+ tree: &mut RandomizedElementTree,+ kind: RandomizedElementTreeMutationKind,+ cx: &mut Context<RandomizedElementTree>,+ ) {+ match tree.apply_mutation(kind, cx) {+ RandomizedElementTreeMutation::Inserted { .. } => self.size += 1,+ RandomizedElementTreeMutation::Removed {+ removed_element_count,+ ..+ } => self.size = self.size.saturating_sub(removed_element_count),+ _ => {}+ }+ }++ /// Applies one change. Weights are percentages of changes. Returns a new window size+ /// when the change is a resize, which the caller applies outside the window update.+ fn change(+ &mut self,+ tree: &mut RandomizedElementTree,+ window: &mut Window,+ cx: &mut Context<RandomizedElementTree>,+ ) -> Option<gpui::Size<gpui::Pixels>> {+ use RandomizedElementTreeMutationKind::*;+ let roll = self.rng.random_range(0..100);+ match roll {+ 0..30 => {+ let kind = [ChildColor, ChildOpacity, ChildBorder][self.rng.random_range(0..3)];+ self.apply(tree, kind, cx);+ }+ 30..40 => self.apply(tree, ChildBounds, cx),+ 40..45 => self.apply(tree, ChildClipping, cx),+ 45..48 => self.apply(tree, ChildVisibility, cx),+ 48..52 => {+ let kind = self.root_kinds[self.rng.random_range(0..self.root_kinds.len())];+ self.apply(tree, kind, cx);+ }+ // Inserts add one element and removals take a leaf or a whole subtree, so+ // grow back toward the initial size after a large removal.+ 52..64 => {+ let kind = if self.size < self.initial_size {+ Insert+ } else if self.rng.random_bool(0.5) {+ Remove+ } else {+ RemoveLeaf+ };+ self.apply(tree, kind, cx);+ }+ 64..70 => self.apply(tree, Reorder, cx),+ 70..74 => {+ let count = (self.size / 20).max(1);+ tree.recolor_children(count, ChangeLocality::Spread, cx);+ }+ 74..84 => {+ let position = self.pointer_position();+ window.dispatch_event(+ gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent {+ position,+ modifiers: gpui::Modifiers::default(),+ pressed_button: None,+ }),+ cx,+ );+ }+ 84..92 => {+ let position = self.pointer_position();+ let distance = gpui::px(self.input_rng.random_range(-160.0..160.0));+ let delta = if self.input_rng.random_bool(0.8) {+ gpui::point(gpui::px(0.), distance)+ } else {+ gpui::point(distance, gpui::px(0.))+ };+ window.dispatch_event(+ gpui::PlatformInput::Scroll(gpui::ScrollEvent {+ position,+ delta: gpui::ScrollDelta::Pixels(delta),+ ..Default::default()+ }),+ cx,+ );+ }+ 92..95 => window.focus_next(cx),+ // Sizes on both sides of the tree's root, which shrinks to fit a smaller window.+ 95..98 => {+ return Some(gpui::size(+ gpui::px(self.input_rng.random_range(480.0..1600.0)),+ gpui::px(self.input_rng.random_range(360.0..1000.0)),+ ));+ }+ _ => cx.notify(),+ }+ None+ }+}++/// One mixed-workload iteration's window, tree and workload, built before timing and+/// removed after it.+struct MixedRun<'a, 'measurement> {+ window: gpui::BenchWindowContext<'a, 'measurement>,+ tree: Entity<RandomizedElementTree>,+ workload: MixedWorkload,+}++impl Drop for MixedRun<'_, '_> {+ fn drop(&mut self) {+ self.window.update(|window, _| window.remove_window());}}+fn measure_mixed(+ family: &TreeFamily,+ input: &TreeInput,+ cached_views: bool,+ cx: &mut BenchAppContext,+) {+ let config = input+ .config+ .with_cached_views(cached_views)+ .with_hover_styles(true)+ .with_animation_density(0.15);+ // Every iteration starts from the same freshly built tree and RNG state, so every+ // iteration applies exactly the same changes, however many Criterion runs.+ cx.bench_batched_task(+ |cx| {+ let mut window = cx.add_empty_window();+ let tree = window.update(|window, cx| {+ window.replace_root(cx, |_, cx| {+ RandomizedElementTree::new_with_config(config, cx)+ })+ });+ cx.run_until_idle();+ window.update(|window, _| window.refresh());+ cx.run_until_idle();+ let initial_size = tree.read_with(cx, |tree, _| tree.snapshot().descendant_count());+ MixedRun {+ window,+ tree,+ workload: MixedWorkload::new(config.seed(), initial_size, cached_views),+ }+ },+ |run, cx| {+ // A change that leaves the window clean draws nothing, as in a real window, so+ // this counts changes, not frames. Animated entities make most changes draw.+ for _ in 0..family.mixed_changes {+ let resize = run.window.update(|window, cx| {+ run.tree+ .update(cx, |tree, cx| run.workload.change(tree, window, cx))+ });+ if let Some(size) = resize {+ run.window.simulate_resize(size);+ }+ cx.run_until_idle();+ }+ gpui::Task::ready(())+ },+ );+}++/// The general benchmark: many kinds of change, one per frame, in a seeded random order,+/// with some entities animating every frame. One iteration applies the family's+/// `mixed_changes` changes to a freshly built tree; the single-change groups explain where+/// a difference here comes from.+#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "RandomizedTree/mixed", fps = 120)]+fn mixed(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let input = family.sample(&mut rng);+ measure_mixed(family, &input, false, cx);+}++/// The same tree with every entity boundary wrapped in a definite-size `.cached()` view,+/// as Zed does for panes and docks, so a frame can reuse clean entities' output.+fn cached_input(family: &TreeFamily, rng: &mut StdRng) -> TreeInput {+ let mut input = family.sample(rng);+ input.config = input.config.with_cached_views(true);+ input+}++#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "CachedTree/full refresh", fps = 120)]+fn cached_full_refresh(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let input = cached_input(family, &mut rng);+ measure_in_window("cached full refresh", &input, cx, |_, window, _| {+ window.refresh()+ });+}++#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "CachedTree/element style", fps = 120)]+fn cached_element_style(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let input = cached_input(family, &mut rng);+ measure_element_style("cached element style", &input, cx);+}++#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "CachedTree/leaf bounds", fps = 120)]+fn cached_leaf_bounds(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let input = cached_input(family, &mut rng);+ measure("cached leaf bounds", &input, cx, |tree, cx| {+ tree.apply_mutation(RandomizedElementTreeMutationKind::ChildBounds, cx);+ });+}++#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "CachedTree/insert-remove", fps = 120)]+fn cached_insert_remove(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let input = cached_input(family, &mut rng);+ let mut insert = true;+ measure("cached insert-remove", &input, cx, |tree, cx| {+ let kind = if insert {+ RandomizedElementTreeMutationKind::Insert+ } else {+ RandomizedElementTreeMutationKind::RemoveLeaf+ };+ tree.apply_mutation(kind, cx);+ insert = !insert;+ });+}++#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "CachedTree/hover", fps = 120)]+fn cached_hover(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let mut input = cached_input(family, &mut rng);+ input.config = input.config.with_hover_styles(true);+ measure_hover("cached hover", &input, cx);+}++#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "CachedTree/mixed", fps = 120)]+fn cached_mixed(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let input = family.sample(&mut rng);+ measure_mixed(family, &input, true, cx);+}++#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "CachedTree/reorder", fps = 120)]+fn cached_reorder(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) {+ let input = cached_input(family, &mut rng);+ measure("cached reorder", &input, cx, |tree, cx| {+ tree.apply_mutation(RandomizedElementTreeMutationKind::Reorder, cx);+ });+}+/// A tree family, the share of its elements that change each frame, and where those/// changes sit.#[derive(Clone)]@@ -555,27 +887,656 @@ fn changing_share(input: &ChangingShareInput, mut rng: StdRng, cx: &mut BenchApp} else {(input.share_percent * element_count).div_ceil(100).max(1)};- let mut last = RecoloredChildren {- recolored: 0,- notified: 0,- };let group = format!("changing share f{}-{}",input.share_percent,input.locality_name());- let frames = measure(&group, tree, cx, |tree, cx| {+ measure(&group, tree, cx, |tree, cx| {if per_frame == 0 {cx.notify();} else {- last = tree.recolor_children(per_frame, input.locality, cx);+ tree.recolor_children(per_frame, input.locality, cx);+ }+ });+}++struct TextPanel {+ index: usize,+ value: u32,+}++impl Render for TextPanel {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let value = self.value;+ gpui::div()+ .id(gpui::ElementId::NamedInteger(+ "text-panel".into(),+ self.index as u64,+ ))+ .flex()+ .flex_col()+ .w(gpui::px(220.))+ .h(gpui::px(192.))+ .bg(gpui::rgb(0x181818))+ .overflow_hidden()+ .children((0..64).map(|label| {+ gpui::div()+ .flex_shrink_0()+ .h(gpui::px(16.))+ .child(format!("Metric {label:02}: {value:06}"))+ }))+ }+}++struct TextPanelRoot {+ panels: Vec<Entity<TextPanel>>,+ font_family: gpui::SharedString,+}++impl TextPanelRoot {+ fn new(panel_count: usize, font_family: &'static str, cx: &mut Context<Self>) -> Self {+ Self {+ panels: (0..panel_count)+ .map(|index| cx.new(|_| TextPanel { index, value: 0 }))+ .collect(),+ font_family: font_family.into(),+ }+ }+}++impl Render for TextPanelRoot {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ gpui::div()+ .id("text-panels")+ .flex()+ .flex_wrap()+ .font_family(self.font_family.clone())+ .text_size(gpui::px(12.))+ .text_color(gpui::rgb(0xffffff))+ .child("0123456789")+ .children(self.panels.iter().cloned())+ }+}++/// Whether this build shapes and rasterizes text with the platform's real text system.+/// Without it, text workloads paint no glyphs, so they are skipped rather than measured.+fn text_shaping_available() -> bool {+ if cfg!(all(+ target_os = "linux",+ not(any(feature = "x11", feature = "wayland"))+ )) {+ eprintln!("text benchmarks require x11 or wayland on Linux for production text shaping");+ false+ } else if cfg!(all(target_os = "macos", not(feature = "font-kit"))) {+ eprintln!("text benchmarks require font-kit on macOS for production text shaping");+ false+ } else if cfg!(target_os = "windows") {+ eprintln!("text benchmarks are unavailable on Windows: headless platforms shape no text");+ false+ } else {+ true+ }+}++fn text_panel_counts() -> Vec<usize> {+ if text_shaping_available() {+ vec![8, 32, 96]+ } else {+ Vec::new()+ }+}++#[gpui::bench(inputs = text_panel_counts(), input_name = "panels", group = "TextPanels/two updates", fps = 120)]+fn text_panel_updates(panel_count: &usize, cx: &mut BenchAppContext) {+ measure_text_panel_updates(*panel_count, "monospace", cx);+}++/// A monospace family the text workloads name explicitly, so they measure shaping and+/// rasterization with one known font rather than whatever the platform's `monospace`+/// fallback resolves to. Linux machines must install it; macOS ships it.+#[cfg(target_os = "macos")]+const INSTALLED_FONT: &str = "Menlo";+#[cfg(not(target_os = "macos"))]+const INSTALLED_FONT: &str = "Noto Sans Mono";++/// Fails setup, before anything is measured, if the named font would fall back to another+/// family: the workload would then measure a different font than its name says.+fn require_installed_font(cx: &BenchAppContext) {+ let font = gpui::font(INSTALLED_FONT);+ let text_system = cx.read(|cx| cx.text_system().clone());+ let font_id = text_system.resolve_font(&font);+ assert_eq!(+ text_system.get_font_for_id(font_id).map(|font| font.family),+ Some(font.family),+ "the text benchmarks require {INSTALLED_FONT} to be installed"+ );+}++#[gpui::bench(inputs = text_panel_counts(), input_name = "panels", group = "TextPanels/installed font two updates", fps = 120)]+fn installed_font_panel_updates(panel_count: &usize, cx: &mut BenchAppContext) {+ require_installed_font(cx);+ measure_text_panel_updates(*panel_count, INSTALLED_FONT, cx);+}++/// Two panels' text changes each frame; the other panels are unchanged.+fn measure_text_panel_updates(+ panel_count: usize,+ font_family: &'static str,+ cx: &mut BenchAppContext,+) {+ let mut window = cx.add_empty_window();+ let root = window.update(|window, cx| {+ window.replace_root(cx, |_, cx| TextPanelRoot::new(panel_count, font_family, cx))+ });+ cx.run_until_idle();+ window.update(|window, _| window.refresh());+ cx.run_until_idle();+ cx.bench_renderer(root, |root, _, cx| {+ for index in [0, panel_count / 2] {+ if let Some(panel) = root.panels.get(index) {+ panel.update(cx, |panel, cx| {+ panel.value = (panel.value + 1) % 1_000_000;+ cx.notify();+ });+ }+ }+ });+ window.update(|window, _| report_scene_stats("TextPanels", &panel_count.to_string(), window));+ window.update(|window, _| window.remove_window());+}++/// Keeps a populated window alive until Criterion drops the measured task's output,+/// so teardown isn't timed.+struct PopulatedWindow(gpui::AsyncWindowContext);++impl Drop for PopulatedWindow {+ fn drop(&mut self) {+ if let Err(error) = self.0.update(|window, _| window.remove_window()) {+ eprintln!("failed to remove populated window: {error}");+ }+ }+}++fn populate(window: &mut Window, cx: &mut gpui::App, panel_count: usize) -> PopulatedWindow {+ window.replace_root(cx, |_, cx| {+ TextPanelRoot::new(panel_count, INSTALLED_FONT, cx)+ });+ PopulatedWindow(window.to_async(cx))+}++thread_local! {+ static DESCRIBED_FIRST_POPULATED: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) };+}++/// Mounting a window full of text and drawing its first frame, from layout through present.+#[gpui::bench(inputs = text_panel_counts(), input_name = "panels", group = "TextPanels/first populated installed font", fps = 120)]+fn first_populated_text_panels(panel_count: &usize, cx: &mut BenchAppContext) {+ let panel_count = *panel_count;+ require_installed_font(cx);++ let describe = DESCRIBED_FIRST_POPULATED.with(|described| {+ let mut described = described.borrow_mut();+ if described.contains(&panel_count) {+ false+ } else {+ described.push(panel_count);+ true+ }+ });+ if describe {+ // Font resolution above is shared setup, not memory the window holds.+ let before_window = bench_metrics::allocation_stats();+ let mut window = cx.add_empty_window();+ let before_population = bench_metrics::allocation_stats();+ let populated = window.update(|window, cx| populate(window, cx, panel_count));+ cx.run_until_idle();+ let after_population = bench_metrics::allocation_stats();+ match before_window.zip(before_population).zip(after_population) {+ Some(((before, empty), after)) => eprintln!(+ "first populated panels: {panel_count}, family {INSTALLED_FONT}; live heap before window {} B, empty window {} B, populated {} B; population delta {} B (process-wide estimates, not exclusive window ownership)",+ before.live_bytes(),+ empty.live_bytes(),+ after.live_bytes(),+ after.live_bytes() - empty.live_bytes(),+ ),+ None => eprintln!("first populated panels: {panel_count}, family {INSTALLED_FONT}"),+ }+ window.update(|window, _| {+ report_scene_stats(+ "TextPanels first populated",+ &panel_count.to_string(),+ window,+ );+ });+ drop(populated);+ cx.run_until_idle();+ }++ cx.bench_batched_task(+ |cx| cx.add_empty_window(),+ |window, _| {+ let populated = window.update(|window, cx| populate(window, cx, panel_count));+ // bench_batched_task delivers pending production frame callbacks+ // before polling this ready task, so layout through present is timed.+ gpui::Task::ready(populated)+ },+ );+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Churn {+ Replace,+ Remount,+ Id,+ Text,+}++impl fmt::Display for Churn {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str(match self {+ Self::Replace => "replace-8-of-96",+ Self::Remount => "remount-48-of-96",+ Self::Id => "id-and-anonymous-count",+ Self::Text => "text-96",+ })+ }+}++struct ChurnPanel {+ index: usize,+ frame: usize,+ workload: Churn,+}++impl Render for ChurnPanel {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let id = if self.workload == Churn::Id {+ self.frame * 96 + self.index+ } else {+ self.index+ };+ // Checkpoints are multiples of ten, so their live shapes are identical.+ let labels = if self.workload == Churn::Id {+ 56 + self.frame % 10+ } else {+ 64+ };+ let value = if self.workload == Churn::Id {+ 0+ } else {+ self.frame % 1_000_000+ };+ gpui::div()+ .id(gpui::ElementId::NamedInteger(+ "churn-panel".into(),+ id as u64,+ ))+ .flex()+ .flex_col()+ .w(gpui::px(220.))+ .h(gpui::px(192.))+ .bg(gpui::rgb(0x181818))+ .overflow_hidden()+ .children((0..labels).map(|label| {+ gpui::div()+ .flex_shrink_0()+ .h(gpui::px(16.))+ .child(format!("Metric {label:02}: {value:06}"))+ }))+ }+}++struct ChurnRoot {+ panels: Vec<Entity<ChurnPanel>>,+ workload: Churn,+ frame: usize,+}++impl ChurnRoot {+ fn new(workload: Churn, cx: &mut Context<Self>) -> Self {+ Self {+ panels: (0..96)+ .map(|index| {+ cx.new(|_| ChurnPanel {+ index,+ frame: 0,+ workload,+ })+ })+ .collect(),+ workload,+ frame: 0,+ }+ }++ fn visible_panels(&self) -> usize {+ if self.workload == Churn::Remount && self.frame % 2 == 1 {+ 48+ } else {+ 96+ }+ }++ fn advance(&mut self, cx: &mut Context<Self>) {+ self.frame += 1;+ match self.workload {+ Churn::Replace => {+ for offset in 0..8 {+ let index = ((self.frame - 1) * 8 + offset) % 96;+ let replacement = cx.new(|_| ChurnPanel {+ index,+ frame: self.frame,+ workload: self.workload,+ });+ if let Some(panel) = self.panels.get_mut(index) {+ *panel = replacement;+ }+ }+ }+ Churn::Id | Churn::Text => {+ for panel in &self.panels {+ panel.update(cx, |panel, cx| {+ panel.frame = self.frame;+ cx.notify();+ });+ }+ }+ Churn::Remount => {}+ }+ cx.notify();+ }+}++impl Render for ChurnRoot {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ gpui::div()+ .id("churn-root")+ .flex()+ .flex_wrap()+ .font_family(INSTALLED_FONT)+ .text_size(gpui::px(12.))+ .text_color(gpui::rgb(0xffffff))+ .child("0123456789")+ .children(self.panels.iter().take(self.visible_panels()).cloned())+ }+}++fn churn_workloads() -> Vec<Churn> {+ if text_shaping_available() {+ vec![Churn::Replace, Churn::Remount, Churn::Id, Churn::Text]+ } else {+ Vec::new()+ }+}++thread_local! {+ static HEAP_CHECKED_CHURN: RefCell<Vec<Churn>> = const { RefCell::new(Vec::new()) };+}++/// A leak check, once per workload and process, before timing: runs a 500-frame window+/// lifetime and prints the live heap at checkpoints. Steady growth across checkpoints+/// means per-frame state, such as element state, layout nodes or text layouts, is being+/// kept alive.+fn report_churn_heap(workload: Churn, cx: &mut BenchAppContext) {+ let first = HEAP_CHECKED_CHURN.with(|checked| {+ let mut checked = checked.borrow_mut();+ let first = !checked.contains(&workload);+ if first {+ checked.push(workload);+ }+ first+ });+ if !first {+ return;+ }+ let before_window = bench_metrics::allocation_stats();+ let mut window = cx.add_empty_window();+ let root =+ window.update(|window, cx| window.replace_root(cx, |_, cx| ChurnRoot::new(workload, cx)));+ cx.run_until_idle();+ let mut checkpoints = Vec::with_capacity(4);+ checkpoints.push((0, bench_metrics::allocation_stats()));+ for frame in 1..=500 {+ window.update(|_, cx| root.update(cx, |root, cx| root.advance(cx)));+ cx.run_until_idle();+ if [50, 200, 500].contains(&frame) {+ checkpoints.push((frame, bench_metrics::allocation_stats()));+ }+ }+ window.update(|window, _| window.remove_window());+ drop(root);+ cx.run_until_idle();+ // Logging allocates, so it waits until every heap reading is taken.+ for (frame, stats) in checkpoints {+ match before_window.zip(stats) {+ Some((before, after)) => eprintln!(+ "layout churn {workload}: frame {frame}, live heap {} B, window delta {} B (process-wide requested bytes)",+ after.live_bytes(),+ after.live_bytes() - before.live_bytes(),+ ),+ None => eprintln!("layout churn {workload}: frame {frame}, heap unavailable"),+ }+ }+}++#[gpui::bench(inputs = churn_workloads(), input_name = "workload", group = "LayoutChurn", fps = 120)]+fn layout_churn(workload: &Churn, cx: &mut BenchAppContext) {+ require_installed_font(cx);+ report_churn_heap(*workload, cx);+ let mut window = cx.add_empty_window();+ let root =+ window.update(|window, cx| window.replace_root(cx, |_, cx| ChurnRoot::new(*workload, cx)));+ cx.run_until_idle();+ cx.bench_renderer(root, |root, _, cx| root.advance(cx));+ window.update(|window, _| window.remove_window());+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum ScrollWorkload {+ Text,+ Virtual,+ Nested,+}++impl fmt::Display for ScrollWorkload {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str(match self {+ Self::Text => "editor-like-text",+ Self::Virtual => "uniform-list",+ Self::Nested => "pane-with-static-siblings",+ })+ }+}++struct ScrollPane {+ workload: ScrollWorkload,+ handle: gpui::ScrollHandle,+ list_handle: gpui::UniformListScrollHandle,+ distance: f32,+ direction: f32,+}++impl ScrollPane {+ fn advance(&mut self, cx: &mut Context<Self>) {+ // Reverse before either boundary: every measured frame changes the viewport,+ // even in long Criterion calibration runs.+ if self.distance >= 6000.0 {+ self.direction = -1.0;+ } else if self.distance <= 600.0 {+ self.direction = 1.0;+ }+ self.distance += self.direction * 12.0;+ self.handle+ .set_offset(gpui::point(gpui::px(0.0), gpui::px(-self.distance)));+ cx.notify();+ }++ fn row(index: usize) -> impl IntoElement {+ gpui::div()+ .flex()+ .h(gpui::px(22.0))+ .flex_shrink_0()+ .child(+ gpui::div()+ .w(gpui::px(64.0))+ .text_color(gpui::rgb(0x858585))+ .child(format!("{index:5}")),+ )+ .child(gpui::div().text_color(gpui::rgb(0xc586c0)).child("let "))+ .child(+ gpui::div()+ .text_color(gpui::rgb(0x9cdcfe))+ .child(format!("line_{index}")),+ )+ .child(+ gpui::div()+ .text_color(gpui::rgb(0xd4d4d4))+ .child(" = document.visible_lines(viewport);"),+ )+ }+}++impl Render for ScrollPane {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let container = gpui::div()+ .size_full()+ .font_family(INSTALLED_FONT)+ .text_size(gpui::px(14.0))+ .bg(gpui::rgb(0x202020));+ if self.workload == ScrollWorkload::Virtual {+ container+ .child(+ gpui::uniform_list(+ "scroll-rows",+ 5000,+ cx.processor(|_, range: std::ops::Range<usize>, _, _| {+ range.map(Self::row).collect()+ }),+ )+ .size_full()+ .track_scroll(&self.list_handle),+ )+ .into_any_element()+ } else {+ container+ .id("scroll-text")+ .overflow_y_scroll()+ .track_scroll(&self.handle)+ .children((0..1000).map(Self::row))+ .into_any_element()}+ }+}++struct ScrollStaticPanel {+ status: bool,+}++impl Render for ScrollStaticPanel {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ gpui::div()+ .size_full()+ .bg(gpui::rgb(0x303030))+ .text_color(gpui::rgb(0xcccccc))+ .children((0..if self.status { 1 } else { 40 }).map(|index| {+ gpui::div().h(gpui::px(22.0)).child(format!(+ "{} {index}",+ if self.status { "Status" } else { "File" }+ ))+ }))+ }+}++struct ScrollRoot {+ pane: Entity<ScrollPane>,+ sidebar: Entity<ScrollStaticPanel>,+ status: Entity<ScrollStaticPanel>,+ nested: bool,+}++impl Render for ScrollRoot {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ gpui::div()+ .size_full()+ .flex()+ .flex_col()+ .child(+ gpui::div()+ .flex()+ .flex_1()+ .min_h_0()+ .when(self.nested, |element| {+ element.child(+ gpui::div()+ .w(gpui::px(220.0))+ .h_full()+ .child(self.sidebar.clone()),+ )+ })+ .child(+ gpui::div()+ .flex_1()+ .min_w_0()+ .h_full()+ .overflow_hidden()+ .child(self.pane.clone()),+ ),+ )+ .when(self.nested, |element| {+ element.child(gpui::div().h(gpui::px(28.0)).child(self.status.clone()))+ })+ }+}++fn scroll_workloads() -> Vec<ScrollWorkload> {+ if text_shaping_available() {+ vec![+ ScrollWorkload::Text,+ ScrollWorkload::Virtual,+ ScrollWorkload::Nested,+ ]+ } else {+ Vec::new()+ }+}++/// Warm pixel scrolling, including the same owner notification as a wheel handler.+/// The text case deliberately materializes lines; the list case is viewport-bounded.+#[gpui::bench(inputs = scroll_workloads(), input_name = "workload", group = "Scroll", fps = 360)]+fn scroll(workload: &ScrollWorkload, cx: &mut BenchAppContext) {+ let mut window = cx.add_empty_window();+ let pane = window.update(|window, cx| {+ let pane = cx.new(|_| {+ let list_handle = gpui::UniformListScrollHandle::new();+ let handle = if *workload == ScrollWorkload::Virtual {+ list_handle.0.borrow().base_handle.clone()+ } else {+ gpui::ScrollHandle::new()+ };+ ScrollPane {+ workload: *workload,+ handle,+ list_handle,+ distance: 600.0,+ direction: 1.0,+ }+ });+ window.replace_root(cx, |_, cx| ScrollRoot {+ pane: pane.clone(),+ sidebar: cx.new(|_| ScrollStaticPanel { status: false }),+ status: cx.new(|_| ScrollStaticPanel { status: true }),+ nested: *workload == ScrollWorkload::Nested,+ });+ pane});- assert!(frames > 0);- if per_frame > 0 {- assert_eq!(last.recolored, per_frame.min(element_count));- assert!(last.notified >= 1);+ cx.run_until_idle();+ for _ in 0..8 {+ window.update(|_, cx| pane.update(cx, |pane, cx| pane.advance(cx)));+ cx.run_until_idle();}+ cx.bench_renderer(pane, |pane, _, cx| pane.advance(cx));+ window.update(|window, _| window.remove_window());}// Frames take 0.4 to 2.5 ms, so a 1 s measurement is already hundreds to thousands of@@ -589,13 +1550,27 @@ gpui::bench_group!(.measurement_time(Duration::from_secs(1)).sample_size(20);targets = full_refresh,+ cached_full_refresh,+ cached_element_style,+ cached_leaf_bounds,+ cached_insert_remove,+ cached_reorder,+ cached_hover,+ cached_mixed,unchanged,- leaf_style,+ element_style,leaf_bounds,root_layout,insert_remove,reorder,+ hover,+ mixed,changing_share,+ text_panel_updates,+ installed_font_panel_updates,+ first_populated_text_panels,+ layout_churn,+ scroll,family_summary);gpui::bench_main!(benches);diff --git a/script/gpui-bench-compare b/script/gpui-bench-comparenew file mode 100755index 00000000000..15d2d1ca581--- /dev/null+++ b/script/gpui-bench-compare@@ -0,0 +1,367 @@+#!/usr/bin/env python3+"""Build two revisions once, then alternate bounded GPUI benchmark runs.++Usage: script/gpui-bench-compare BASELINE CANDIDATE+ script/gpui-bench-compare BASELINE CANDIDATE --filter 'TextPanels/'++The invoking checkout's three benchmark files, randomized tree fixture and bench+macro are used for BOTH revisions, so both revisions must provide the GPUI+benchmark APIs they call. Sources, build artifacts, binaries, raw logs, Criterion+samples and summary.json persist under target/gpui-bench-compare. Nothing+switches the invoking checkout or publishes a branch.++The default core suite keeps the mixed workload (plain and with cached views),+five full-refresh tree shapes, element style, cached element style, pointer+hover, warm installed-font text, text first frame, three scrolling workloads,+random and patterned primitive painting, and two inspector workloads. --full+selects every variant; --slow restores the benchmarks' own Criterion settings+(including inspector's five-second measurement). --repetitions controls+independent runs, not random seeds. Use --seed to compare another fixed tree.++Foreground retired instructions are primary. Linux needs perf access+(CAP_PERFMON or perf_event_paranoid <= 2); macOS needs Apple Silicon. Frames run+the production pipeline through the platform's headless GPU renderer, so they+include scene encoding and GPU submission; GPU execution itself runs on other+threads and isn't counted. Wall-time medians include calibration samples; raw+logs retain frame metrics. Spread is the full range of independent run medians+divided by their median, not a confidence interval. Warnings also flag wide+within-run sample ranges; even slow settings can drift, so inspect raw samples+before judging small changes. Do not run competing benchmarks on the same machine.+Requires Python 3.12+ on Linux or macOS.+"""++import argparse+import fcntl+import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import signal+import statistics+import subprocess+import sys+import tarfile+import time+++TARGETS = ("randomized_element_tree", "primitives", "inspector_render")+FIXTURE_FILES = tuple(+ Path("crates/gpui_platform/benches") / f"{target}.rs" for target in TARGETS+) + (+ Path("crates/gpui_macros/src/bench.rs"),+ Path("crates/gpui/src/randomized_element_tree.rs"),+)+CORE = {+ "randomized_element_tree": (+ r"^((Randomized|Cached)Tree/mixed/tree/mixed/|"+ r"RandomizedTree/full refresh/tree/|"+ r"RandomizedTree/element style/tree/mixed/|"+ r"CachedTree/element style/tree/mixed/|"+ r"RandomizedTree/hover/tree/mixed/|"+ r"Scroll/workload/|"+ r"TextPanels/installed font two updates/panels/32$|"+ r"TextPanels/first populated installed font/panels/32$)"+ ),+ # Overlapping paint cases, including the random ones with large paths and text,+ # primarily stress GPU overdraw, not draw ordering; GPU queue backpressure makes+ # their instruction counts vary by up to ~16% within a run.+ "primitives": (+ r"^Primitives/(scene/[a-z]+-1024(-seed-\d+)?|paint/case/grid-1024)$"+ ),+ "inspector_render": (+ r"^closed_inspector_(grid/case/1000-nodes|panel/case/500-rows)-0-cycles$"+ ),+}+FAST = [+ "--warm-up-time", "0.05",+ "--measurement-time", "0.3",+ "--sample-size", "10",+ "--nresamples", "1000",+]+++def run(command, *, cwd, environment, log, timeout):+ started = time.monotonic()+ with log.open("w") as output:+ # A session of its own lets a timeout or interrupt stop the whole process tree:+ # killing only Cargo would leave its compiler and build-script children running+ # after this script exits and releases the comparison lock.+ process = subprocess.Popen(+ command, cwd=cwd, env=environment, stdout=output,+ stderr=subprocess.STDOUT, start_new_session=True,+ )+ try:+ returncode = process.wait(timeout=timeout)+ except BaseException as error:+ os.killpg(process.pid, signal.SIGKILL)+ process.wait()+ if isinstance(error, subprocess.TimeoutExpired):+ raise RuntimeError(f"{error}; see {log}") from error+ raise+ if returncode != 0:+ raise RuntimeError(f"{command[0]} exited with status {returncode}; see {log}")+ return time.monotonic() - started+++def git(root, *arguments):+ return subprocess.check_output(["git", "-C", str(root), *arguments], text=True).strip()+++def prepare(root, cache, revision, features, timeout, environment):+ commit = git(root, "rev-parse", "--verify", f"{revision}^{{commit}}")+ source = cache / "sources" / commit+ source.mkdir(parents=True, exist_ok=True)+ if not (source / ".archive-complete").exists():+ archive = cache / f"{commit}.tar"+ with archive.open("wb") as output:+ subprocess.run(["git", "-C", str(root), "archive", commit],+ stdout=output, check=True, timeout=timeout)+ with tarfile.open(archive) as contents:+ contents.extractall(source, filter="data")+ (source / ".archive-complete").touch()+ digest = hashlib.sha256()+ for relative in FIXTURE_FILES:+ content = (root / relative).read_bytes()+ digest.update(str(relative).encode())+ digest.update(content)+ destination = source / relative+ if not destination.exists() or destination.read_bytes() != content:+ destination.write_bytes(content)+ build_key = hashlib.sha256(+ (commit + digest.hexdigest() + features).encode()+ ).hexdigest()[:20]+ artifacts = cache / "binaries" / build_key+ artifacts.mkdir(parents=True, exist_ok=True)+ # Cargo's workspace fingerprints use mtimes, not source contents. Archives+ # from different commits can otherwise reuse the preceding revision's binary.+ environment = dict(environment, CARGO_TARGET_DIR=str(cache / "build" / commit))+ feature_log = artifacts / "features.log"+ run(+ ["cargo", "tree", "--locked", "-p", "gpui_platform", "--features", features,+ "-e", "normal,build,dev,features"],+ cwd=source, environment=environment, log=feature_log, timeout=timeout,+ )+ if 'feature "test-support"' in feature_log.read_text():+ raise RuntimeError(f"benchmark graph enables test-support: {feature_log}")+ command = [+ "cargo", "bench", "--locked", "-p", "gpui_platform", "--features", features,+ "--profile", "release-fast", "--no-run", "--message-format=json",+ ]+ for target in TARGETS:+ command += ["--bench", target]+ elapsed = run(command, cwd=source, environment=environment,+ log=artifacts / "build.log", timeout=timeout)+ binaries = {}+ for line in (artifacts / "build.log").read_text().splitlines():+ try:+ message = json.loads(line)+ except json.JSONDecodeError:+ continue+ if message.get("reason") != "compiler-artifact" or not message.get("executable"):+ continue+ name = message["target"]["name"]+ if name in TARGETS:+ # Cargo may overwrite these paths on the next revision's build.+ destination = artifacts / name+ shutil.copy2(message["executable"], destination)+ binaries[name] = destination+ if set(binaries) != set(TARGETS):+ raise RuntimeError(f"missing benchmark executable; see {artifacts / 'build.log'}")+ binary_hashes = {}+ for target, binary in binaries.items():+ with binary.open("rb") as executable:+ binary_hashes[target] = hashlib.file_digest(executable, "sha256").hexdigest()+ return {+ "revision": revision, "commit": commit, "build_seconds": elapsed,+ "gpui_tree": git(root, "rev-parse", f"{commit}:crates/gpui"),+ "binary_sha256": binary_hashes,+ "benchmark_sha256": digest.hexdigest(),+ "lockfile_sha256": hashlib.sha256((source / "Cargo.lock").read_bytes()).hexdigest(),+ "source": str(source), "binaries": binaries,+ }+++def verify_distinct_artifacts(revisions):+ baseline, candidate = revisions+ if baseline["gpui_tree"] != candidate["gpui_tree"]:+ for target in TARGETS:+ if baseline["binary_sha256"][target] == candidate["binary_sha256"][target]:+ raise RuntimeError(+ f"{target} binaries are byte-identical despite different crates/gpui trees; "+ "refusing a potentially contaminated benchmark comparison"+ )+++def measure(binary, identifier, directory, environment, timeout, slow):+ directory.mkdir(parents=True, exist_ok=True)+ environment = dict(environment, CRITERION_HOME=str(directory / "criterion"))+ command = [str(binary), "--bench", "^" + re.escape(identifier) + "$", "--noplot"]+ if not slow:+ command += FAST+ elapsed = run(command, cwd=directory, environment=environment,+ log=directory / "run.log", timeout=timeout)+ samples = list((directory / "criterion").glob("**/new/sample.json"))+ if len(samples) != 1:+ raise RuntimeError(f"expected one measured case, got {len(samples)}: {directory}")+ sample = json.loads(samples[0].read_text())+ counts = [total / count for total, count in zip(sample["times"], sample["iters"])]+ wall = re.search(+ r"wall time per iteration: median ([\d.]+) (\S+) \(min ([\d.]+), max ([\d.]+)",+ (directory / "run.log").read_text(),+ )+ if wall is None:+ raise RuntimeError(f"missing wall-time secondary: {directory / 'run.log'}")+ units = {"ns": 1e-9, "µs": 1e-6, "us": 1e-6, "ms": 1e-3, "s": 1}+ return {+ "instructions": statistics.median(counts),+ "sample_min": min(counts), "sample_max": max(counts),+ "wall_seconds": float(wall[1]) * units[wall[2]],+ "elapsed_seconds": elapsed, "iterations": sum(sample["iters"]),+ }+++def spread(values):+ return (max(values) - min(values)) / statistics.median(values) * 100+++def main():+ started = time.monotonic()+ parser = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("baseline")+ parser.add_argument("candidate")+ parser.add_argument("--filter", help="Criterion regex, applied to all three binaries")+ parser.add_argument("--full", action="store_true")+ parser.add_argument("--slow", action="store_true")+ parser.add_argument("--repetitions", type=int, default=3)+ parser.add_argument("--seed", type=int, default=0)+ # Text benchmarks need the platform's real text system: x11 on Linux, font-kit on macOS.+ parser.add_argument("--features", default={"linux": "bench-support,x11",+ "darwin": "bench-support,font-kit"}.get(+ sys.platform, "bench-support"))+ parser.add_argument("--timeout", type=int, default=300,+ help="hard timeout for EACH build/run, at most 300 seconds")+ parser.add_argument("--cache", type=Path)+ args = parser.parse_args()+ if not 1 <= args.timeout <= 300 or args.repetitions < 1 or args.seed < 0:+ parser.error("timeout must be 1..300, repetitions positive and seed nonnegative")+ if args.filter and args.full:+ parser.error("--filter and --full are mutually exclusive")+ if "bench-support" not in args.features.split(",") or "test-support" in args.features:+ parser.error("features must include bench-support and must not include test-support")+ root = Path(git(Path(__file__).resolve().parent, "rev-parse", "--show-toplevel"))+ cache = (args.cache or root / "target/gpui-bench-compare").resolve()+ cache.mkdir(parents=True, exist_ok=True)+ lock = (cache / "compare.lock").open("w")+ try:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError as error:+ raise RuntimeError(f"another comparison is using {cache}") from error+ output = cache / "runs" / time.strftime("%Y%m%d-%H%M%S")+ output.mkdir(parents=True, exist_ok=False)+ environment = dict(os.environ, BENCH_MEASUREMENT="foreground-instructions",+ SEED=str(args.seed), ITERATIONS="1")+ environment["PATH"] = str(Path.home() / ".cargo/bin") + os.pathsep + environment["PATH"]+ revisions = []+ for revision in [args.baseline, args.candidate]:+ print(f"Building {revision} (once)...", flush=True)+ revisions.append(prepare(root, cache, revision, args.features, args.timeout, environment))+ verify_distinct_artifacts(revisions)+ if revisions[0]["lockfile_sha256"] != revisions[1]["lockfile_sha256"]:+ print("NOTE: revisions have different Cargo.lock files; dependency changes may affect results.")+ cases = {}+ for target in TARGETS:+ listings = []+ pattern = args.filter if args.filter else "" if args.full else CORE[target]+ for index, revision in enumerate(revisions):+ log = output / f"list-{index}-{target}.log"+ run([str(revision["binaries"][target]), "--list", pattern],+ cwd=output, environment=environment, log=log, timeout=args.timeout)+ listings.append([line.removesuffix(": benchmark") for line in log.read_text().splitlines()+ if line.endswith(": benchmark")])+ if listings[0] != listings[1]:+ raise RuntimeError(f"benchmark IDs differ for {target}")+ cases[target] = listings[0]+ if not any(cases.values()):+ raise RuntimeError("filter selected no benchmarks")+ # Verify all selected paths once; exercise Criterion's quick path before sampling.+ for index, revision in enumerate(revisions):+ for target, identifiers in cases.items():+ if not identifiers:+ continue+ binary = revision["binaries"][target]+ pattern = "^(" + "|".join(re.escape(value) for value in identifiers) + ")$"+ for mode, selection in [("--test", pattern),+ ("--quick", "^" + re.escape(identifiers[0]) + "$")]:+ run([str(binary), "--bench", selection, mode, "--noplot",+ "--measurement-time", "0.3"], cwd=output, environment=environment,+ log=output / f"smoke-{index}-{target}{mode}.log", timeout=args.timeout)+ results = {}+ print("Measuring sequentially; instructions are foreground retired instructions per frame/operation.",+ flush=True)+ print(f"{'benchmark':76} {'base M':>9} {'new M':>9} {'change':>9} "+ f"{'spread B/N':>14} {'wall ms B/N':>17} {'run s B/N':>13}", flush=True)+ for target, identifiers in cases.items():+ for identifier in identifiers:+ pair = [[], []]+ case_number = len(results)+ for repetition in range(args.repetitions):+ for index in ([0, 1] if repetition % 2 == 0 else [1, 0]):+ revision = revisions[index]+ directory = output / f"{case_number:03}-{repetition}-{index}"+ pair[index].append(measure(revision["binaries"][target], identifier, directory,+ environment, args.timeout, args.slow))+ results[identifier] = pair+ instruction_runs = [[value["instructions"] for value in side] for side in pair]+ baseline, candidate = map(statistics.median, instruction_runs)+ walls = [statistics.median(value["wall_seconds"] for value in side) * 1000 for side in pair]+ durations = [statistics.median(value["elapsed_seconds"] for value in side) for side in pair]+ noise = (f"{spread(instruction_runs[0]):5.2f}/{spread(instruction_runs[1]):5.2f}%"+ if args.repetitions > 1 else " n/a")+ print(f"{identifier:76} {baseline / 1e6:9.3f} {candidate / 1e6:9.3f} "+ f"{(candidate / baseline - 1) * 100:+8.2f}% "+ f"{noise} "+ f"{walls[0]:7.3f}/{walls[1]:7.3f} "+ f"{durations[0]:5.2f}/{durations[1]:5.2f}", flush=True)+ if args.repetitions > 1 and any(spread(values) > 1 for values in instruction_runs):+ print(" NOTE: >1% instruction spread; confirm this case with --slow before judging a change.",+ flush=True)+ sample_ranges = [+ max((value["sample_max"] - value["sample_min"]) / value["instructions"] * 100+ for value in side)+ for side in pair+ ]+ if any(value > 1 for value in sample_ranges):+ print(f" NOTE: within-run instruction sample range B/N "+ f"{sample_ranges[0]:.2f}/{sample_ranges[1]:.2f}%; "+ "inspect raw samples for drift/outliers before judging a change.", flush=True)+ summary = {+ "configuration": vars(args) | {"cache": str(cache)},+ "revisions": [{key: value for key, value in revision.items() if key != "binaries"}+ for revision in revisions],+ "results": results,+ "cases": cases,+ "environment": {name: value for name, value in environment.items()+ if name in ("BENCH_MEASUREMENT", "SEED", "ITERATIONS",+ "RUSTFLAGS")},+ }+ (output / "summary.json").write_text(json.dumps(summary, indent=2, default=str) + "\n")+ for index, revision in enumerate(revisions):+ seconds = sum(value["elapsed_seconds"] for pair in results.values() for value in pair[index])+ print(f"{revision['commit'][:12]}: build {revision['build_seconds']:.2f}s, "+ f"measured processes {seconds:.2f}s ({args.repetitions} runs/case)")+ for target, identifiers in cases.items():+ seconds = sum(value["elapsed_seconds"] for identifier in identifiers+ for value in results[identifier][index])+ print(f" {target}: {seconds:.2f}s")+ print(f"Total including builds, discovery, smoke and quick checks: {time.monotonic() - started:.2f}s")+ print(f"Raw samples, frame reports and summary: {output}")+++if __name__ == "__main__":+ try:+ main()+ except (RuntimeError, subprocess.CalledProcessError) as error:+ sys.exit(str(error))