| 1 | use std::{ |
| 2 | cell::{OnceCell, RefCell}, |
| 3 | future::Future, |
| 4 | rc::Rc, |
| 5 | sync::{ |
| 6 | Arc, |
| 7 | atomic::{AtomicBool, Ordering}, |
| 8 | }, |
| 9 | time::{Duration, Instant}, |
| 10 | }; |
| 11 | |
| 12 | use anyhow::{Result, anyhow}; |
| 13 | pub use bench_metrics::{BenchMeasurement, CountingAllocator, MetricReport}; |
| 14 | use hdrhistogram::Histogram; |
| 15 | |
| 16 | use crate::{ |
| 17 | AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, Bounds, Context, Empty, |
| 18 | Entity, EntityId, Focusable, ForegroundExecutor, Global, Platform, PlatformHeadlessRenderer, |
| 19 | PlatformTextSystem, Render, Reservation, Task, TestPlatform, ThreadedDispatcher, VisualContext, |
| 20 | Window, WindowBounds, WindowHandle, WindowOptions, |
| 21 | app::GpuiBorrow, |
| 22 | profiler::{ |
| 23 | self, FrameEvent, FrameTimingCollector, |
| 24 | journal::{ForegroundEvent, ForegroundJournalCollector, ForegroundJournalEntry}, |
| 25 | }, |
| 26 | }; |
| 27 | |
| 28 | /// Returns a benchmark platform backed by this thread's shared dispatcher. |
| 29 | /// |
| 30 | /// The platform uses this thread's shared multithreaded [`ThreadedDispatcher`], so |
| 31 | /// background work runs with production concurrency in real time. The dispatcher |
| 32 | /// is cached per thread and reused across benchmark invocations so worker and |
| 33 | /// timer threads persist for the whole process instead of being recreated for |
| 34 | /// every Criterion calibration pass. |
| 35 | /// |
| 36 | /// Text is shaped with the provided platform text system. Benchmarks generated |
| 37 | /// by `#[gpui::bench]` use the current platform's text system, so text-heavy |
| 38 | /// benchmark measurements include production shaping and glyph rasterization. |
| 39 | /// |
| 40 | /// `headless_renderer_factory` supplies a renderer for benchmark windows, e.g. |
| 41 | /// `gpui_platform::current_headless_renderer`. When present, scenes drawn by |
| 42 | /// benchmarks are rasterized through the real sprite atlas and submitted to |
| 43 | /// the GPU on present, so quad/sprite regressions show up in measurements. |
| 44 | /// When `None`, presenting discards the scene. Currently only macOS provides |
| 45 | /// a headless renderer (Metal), so GPU submission is excluded from benchmark |
| 46 | /// measurements on other platforms. |
| 47 | pub fn bench_platform( |
| 48 | headless_renderer_factory: Option< |
| 49 | Box<dyn Fn() -> anyhow::Result<Option<Box<dyn PlatformHeadlessRenderer>>>>, |
| 50 | >, |
| 51 | text_system: Arc<dyn PlatformTextSystem>, |
| 52 | ) -> Rc<dyn Platform> { |
| 53 | thread_local! { |
| 54 | static DISPATCHER: OnceCell<Arc<ThreadedDispatcher>> = const { OnceCell::new() }; |
| 55 | } |
| 56 | let dispatcher = DISPATCHER.with(|cell| { |
| 57 | cell.get_or_init(|| Arc::new(ThreadedDispatcher::new())) |
| 58 | .clone() |
| 59 | }); |
| 60 | let background_executor = BackgroundExecutor::new(dispatcher.clone()); |
| 61 | let foreground_executor = ForegroundExecutor::new(dispatcher); |
| 62 | TestPlatform::with_platform( |
| 63 | background_executor, |
| 64 | foreground_executor, |
| 65 | text_system, |
| 66 | headless_renderer_factory, |
| 67 | ) as Rc<dyn Platform> |
| 68 | } |
| 69 | |
| 70 | /// Default target frame rate when a benchmark doesn't specify `fps = N`. |
| 71 | const DEFAULT_FPS: u64 = 120; |
| 72 | |
| 73 | const NANOS_PER_SECOND: u128 = 1_000_000_000; |
| 74 | |
| 75 | /// Aggregate statistics for total foreground executor work observed during a |
| 76 | /// measured interval, returned by [`BenchReport::foreground_work`]. |
| 77 | #[derive(Clone, Copy, Debug)] |
| 78 | pub struct ForegroundWorkSummary { |
| 79 | /// Number of foreground work items recorded: task polls, action |
| 80 | /// handlers, input dispatches, and folded sub-floor poll flushes. |
| 81 | pub count: u64, |
| 82 | /// Sum of every recorded item's duration. |
| 83 | pub total: Duration, |
| 84 | /// The longest single recorded item. |
| 85 | pub max: Duration, |
| 86 | /// 50th percentile duration. |
| 87 | pub p50: Duration, |
| 88 | /// 90th percentile duration. |
| 89 | pub p90: Duration, |
| 90 | /// 95th percentile duration. |
| 91 | pub p95: Duration, |
| 92 | /// 99th percentile duration. |
| 93 | pub p99: Duration, |
| 94 | /// How many whole frame budgets (at the report's configured FPS) were |
| 95 | /// exceeded in total, summed across every recorded item. |
| 96 | pub frame_budget_overruns_total: u64, |
| 97 | /// How many whole frame budgets the longest recorded item exceeded. |
| 98 | pub frame_budget_overruns_max: u64, |
| 99 | } |
| 100 | |
| 101 | /// A small report produced by GPUI benchmarks. |
| 102 | #[derive(Clone)] |
| 103 | pub struct BenchReport { |
| 104 | frame_snapshot: Rc<RefCell<WindowFrameSnapshot>>, |
| 105 | metrics: MetricReport, |
| 106 | frame_budget_nanos: u128, |
| 107 | } |
| 108 | |
| 109 | impl Default for BenchReport { |
| 110 | fn default() -> Self { |
| 111 | Self::with_fps(DEFAULT_FPS) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | impl BenchReport { |
| 116 | /// Creates a report whose per-frame budget is one frame at `fps` when |
| 117 | /// counting frame budget overruns. |
| 118 | pub fn with_fps(fps: u64) -> Self { |
| 119 | assert!(fps > 0, "frame rate must be greater than zero"); |
| 120 | Self::with_frame_budget_nanos(NANOS_PER_SECOND / fps as u128) |
| 121 | } |
| 122 | |
| 123 | /// Creates a report that treats `frame_budget_nanos` as the per-frame budget |
| 124 | /// when counting frame budget overruns. |
| 125 | pub fn with_frame_budget_nanos(frame_budget_nanos: u128) -> Self { |
| 126 | assert!( |
| 127 | frame_budget_nanos > 0, |
| 128 | "frame budget must be at least one nanosecond" |
| 129 | ); |
| 130 | Self { |
| 131 | frame_snapshot: Rc::new(RefCell::new(WindowFrameSnapshot::new())), |
| 132 | metrics: MetricReport::new(), |
| 133 | frame_budget_nanos, |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /// Returns the per-iteration secondary metrics (retired instructions, |
| 138 | /// cycles, context switches, ...) recorded alongside Criterion's primary |
| 139 | /// measurement. |
| 140 | pub fn metrics(&self) -> &MetricReport { |
| 141 | &self.metrics |
| 142 | } |
| 143 | |
| 144 | fn record_frame_timings<'i>(&self, events: impl IntoIterator<Item = &'i FrameEvent>) { |
| 145 | let mut snapshot = self.frame_snapshot.borrow_mut(); |
| 146 | // `.ok()` on `record`: this operation is infallible (the histograms auto-resize). |
| 147 | for event in events { |
| 148 | match event { |
| 149 | FrameEvent::Draw(timing) => { |
| 150 | snapshot |
| 151 | .draw |
| 152 | .record(timing.draw_duration().as_nanos() as u64) |
| 153 | .ok(); |
| 154 | if let Some(dirty_to_draw) = timing.dirty_to_draw_duration() { |
| 155 | snapshot |
| 156 | .dirty_to_draw |
| 157 | .record(dirty_to_draw.as_nanos() as u64) |
| 158 | .ok(); |
| 159 | } |
| 160 | if timing.invalidations > 0 { |
| 161 | snapshot |
| 162 | .invalidations_per_frame |
| 163 | .record(timing.invalidations) |
| 164 | .ok(); |
| 165 | } |
| 166 | } |
| 167 | FrameEvent::Present(timing) => { |
| 168 | if let Some(animation_interval) = timing.animation_interval { |
| 169 | snapshot |
| 170 | .present_interval |
| 171 | .record(animation_interval.as_nanos() as u64) |
| 172 | .ok(); |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// Records total foreground executor work observed during a measured |
| 180 | /// interval: task polls, action handlers, and input dispatches, whether |
| 181 | /// or not they produced a window draw. Draws and presents are excluded |
| 182 | /// here since [`Self::record_frame_timings`] already accounts for them. |
| 183 | fn record_foreground_events<'i>(&self, events: impl IntoIterator<Item = &'i ForegroundEvent>) { |
| 184 | let mut snapshot = self.frame_snapshot.borrow_mut(); |
| 185 | for event in events { |
| 186 | let duration = match event { |
| 187 | ForegroundEvent::Draw(_) | ForegroundEvent::Present(_) => continue, |
| 188 | // A flush's span (used by `ForegroundEvent::duration`) is not |
| 189 | // the time spent polling; its summary total is. |
| 190 | ForegroundEvent::SmallPolls(flush) => flush.summary.total, |
| 191 | _ => event.duration(), |
| 192 | }; |
| 193 | snapshot.foreground_work.record(duration); |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | fn total_budget_overruns(&self, histogram: &Histogram<u64>) -> u64 { |
| 198 | histogram |
| 199 | .iter_recorded() |
| 200 | .map(|value| { |
| 201 | self.budget_overruns(Duration::from_nanos(value.value_iterated_to())) |
| 202 | * value.count_at_value() |
| 203 | }) |
| 204 | .sum() |
| 205 | } |
| 206 | |
| 207 | /// Returns how many whole frame budgets `foreground_time` exceeded the |
| 208 | /// per frame budget by. This is a synthetic proxy for missed frames: the |
| 209 | /// benchmark harness has no vsync, so it counts how many frame deadlines |
| 210 | /// would have elapsed while the foreground thread was busy. |
| 211 | fn budget_overruns(&self, foreground_time: Duration) -> u64 { |
| 212 | let foreground_nanos = foreground_time.as_nanos(); |
| 213 | if foreground_nanos <= self.frame_budget_nanos { |
| 214 | return 0; |
| 215 | } |
| 216 | |
| 217 | let over_budget_nanos = foreground_nanos - self.frame_budget_nanos; |
| 218 | over_budget_nanos.div_ceil(self.frame_budget_nanos) as u64 |
| 219 | } |
| 220 | |
| 221 | /// Returns aggregate statistics for total foreground executor work |
| 222 | /// observed during the measured interval: every task poll, action |
| 223 | /// handler, and input dispatch on the foreground thread, whether or not |
| 224 | /// it produced a window draw. This is captured through GPUI's foreground |
| 225 | /// journal, so it requires no window and surfaces a slow or stalled task |
| 226 | /// even when nothing was drawn while it ran. |
| 227 | /// |
| 228 | /// Returns `None` when no foreground work was recorded, e.g. a |
| 229 | /// [`BenchAppContext::bench_iter`] measurement that does no async work. |
| 230 | pub fn foreground_work(&self) -> Option<ForegroundWorkSummary> { |
| 231 | let frame_snapshot = self.frame_snapshot.borrow(); |
| 232 | let foreground_work = &frame_snapshot.foreground_work; |
| 233 | if foreground_work.histogram.is_empty() { |
| 234 | return None; |
| 235 | } |
| 236 | |
| 237 | let max = Duration::from_nanos(foreground_work.histogram.max()); |
| 238 | Some(ForegroundWorkSummary { |
| 239 | count: foreground_work.histogram.len(), |
| 240 | total: Duration::from_nanos(foreground_work.total_nanos), |
| 241 | max, |
| 242 | p50: Duration::from_nanos(foreground_work.histogram.value_at_quantile(0.50)), |
| 243 | p90: Duration::from_nanos(foreground_work.histogram.value_at_quantile(0.90)), |
| 244 | p95: Duration::from_nanos(foreground_work.histogram.value_at_quantile(0.95)), |
| 245 | p99: Duration::from_nanos(foreground_work.histogram.value_at_quantile(0.99)), |
| 246 | frame_budget_overruns_total: self.total_budget_overruns(&foreground_work.histogram), |
| 247 | frame_budget_overruns_max: self.budget_overruns(max), |
| 248 | }) |
| 249 | } |
| 250 | |
| 251 | /// Prints this report to stderr. |
| 252 | pub fn print(&self, benchmark_name: &str) { |
| 253 | let frame_snapshot = self.frame_snapshot.borrow(); |
| 254 | if frame_snapshot.is_empty() && self.metrics.is_empty() { |
| 255 | return; |
| 256 | } |
| 257 | |
| 258 | eprintln!("GPUI bench report (all observed iterations): {benchmark_name}"); |
| 259 | eprintln!(" note: includes Criterion warmup/calibration"); |
| 260 | self.metrics.print(" "); |
| 261 | self.print_histogram("window dirty-to-draw", &frame_snapshot.dirty_to_draw); |
| 262 | self.print_histogram("window draw", &frame_snapshot.draw); |
| 263 | self.print_histogram("window present interval", &frame_snapshot.present_interval); |
| 264 | if !frame_snapshot.invalidations_per_frame.is_empty() { |
| 265 | eprintln!( |
| 266 | " invalidations per frame: mean {:.2}, max {}", |
| 267 | frame_snapshot.invalidations_per_frame.mean(), |
| 268 | frame_snapshot.invalidations_per_frame.max() |
| 269 | ); |
| 270 | } |
| 271 | self.print_foreground_work(&frame_snapshot.foreground_work); |
| 272 | } |
| 273 | |
| 274 | fn print_histogram(&self, name: &str, histogram: &Histogram<u64>) { |
| 275 | if histogram.is_empty() { |
| 276 | return; |
| 277 | } |
| 278 | |
| 279 | eprintln!(" {name}:"); |
| 280 | self.print_histogram_body(histogram); |
| 281 | } |
| 282 | |
| 283 | fn print_foreground_work(&self, foreground_work: &DurationHistogram) { |
| 284 | if foreground_work.histogram.is_empty() { |
| 285 | return; |
| 286 | } |
| 287 | |
| 288 | eprintln!(" foreground executor work (task polls, actions, input dispatch):"); |
| 289 | eprintln!(" note: excludes window draw/present, reported separately above"); |
| 290 | eprintln!( |
| 291 | " total: {}", |
| 292 | format_duration(Duration::from_nanos(foreground_work.total_nanos)) |
| 293 | ); |
| 294 | self.print_histogram_body(&foreground_work.histogram); |
| 295 | } |
| 296 | |
| 297 | fn print_histogram_body(&self, histogram: &Histogram<u64>) { |
| 298 | let max_foreground_time = Duration::from_nanos(histogram.max()); |
| 299 | eprintln!(" samples: {}", histogram.len()); |
| 300 | eprintln!( |
| 301 | " mean: {}", |
| 302 | format_duration(Duration::from_nanos(histogram.mean() as u64)) |
| 303 | ); |
| 304 | eprintln!( |
| 305 | " p50: {}", |
| 306 | format_duration(Duration::from_nanos(histogram.value_at_quantile(0.50))) |
| 307 | ); |
| 308 | eprintln!( |
| 309 | " p90: {}", |
| 310 | format_duration(Duration::from_nanos(histogram.value_at_quantile(0.90))) |
| 311 | ); |
| 312 | eprintln!( |
| 313 | " p95: {}", |
| 314 | format_duration(Duration::from_nanos(histogram.value_at_quantile(0.95))) |
| 315 | ); |
| 316 | eprintln!( |
| 317 | " p99: {}", |
| 318 | format_duration(Duration::from_nanos(histogram.value_at_quantile(0.99))) |
| 319 | ); |
| 320 | eprintln!(" max: {}", format_duration(max_foreground_time)); |
| 321 | eprintln!( |
| 322 | " frame budget overruns total: {}", |
| 323 | self.total_budget_overruns(histogram) |
| 324 | ); |
| 325 | eprintln!( |
| 326 | " frame budget overruns max: {}", |
| 327 | self.budget_overruns(max_foreground_time) |
| 328 | ); |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | struct WindowFrameSnapshot { |
| 333 | dirty_to_draw: Histogram<u64>, |
| 334 | draw: Histogram<u64>, |
| 335 | present_interval: Histogram<u64>, |
| 336 | invalidations_per_frame: Histogram<u64>, |
| 337 | foreground_work: DurationHistogram, |
| 338 | } |
| 339 | |
| 340 | impl WindowFrameSnapshot { |
| 341 | fn new() -> Self { |
| 342 | Self { |
| 343 | dirty_to_draw: Histogram::new(3).expect("3 significant digits is valid"), |
| 344 | draw: Histogram::new(3).expect("3 significant digits is valid"), |
| 345 | present_interval: Histogram::new(3).expect("3 significant digits is valid"), |
| 346 | invalidations_per_frame: Histogram::new(3).expect("3 significant digits is valid"), |
| 347 | foreground_work: DurationHistogram::new(), |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | fn is_empty(&self) -> bool { |
| 352 | self.dirty_to_draw.is_empty() |
| 353 | && self.draw.is_empty() |
| 354 | && self.present_interval.is_empty() |
| 355 | && self.foreground_work.histogram.is_empty() |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | /// A duration histogram paired with an exact running total, since the |
| 360 | /// histogram's bucketed values (3 significant digits) approximate a sum less |
| 361 | /// precisely than tracking it directly. |
| 362 | struct DurationHistogram { |
| 363 | histogram: Histogram<u64>, |
| 364 | total_nanos: u64, |
| 365 | } |
| 366 | |
| 367 | impl DurationHistogram { |
| 368 | fn new() -> Self { |
| 369 | Self { |
| 370 | histogram: Histogram::new(3).expect("3 significant digits is valid"), |
| 371 | total_nanos: 0, |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | fn record(&mut self, duration: Duration) { |
| 376 | let nanos = duration.as_nanos() as u64; |
| 377 | // Infallible: the histogram auto-resizes. |
| 378 | self.histogram.record(nanos).ok(); |
| 379 | self.total_nanos += nanos; |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | fn format_duration(duration: Duration) -> String { |
| 384 | format!("{:.3}ms", duration.as_secs_f64() * 1000.) |
| 385 | } |
| 386 | |
| 387 | /// Enables profiler tracing for a measurement and collects its frame events |
| 388 | /// and foreground journal entries. |
| 389 | /// |
| 390 | /// The previous tracing state is restored on drop, so a panicking measurement |
| 391 | /// doesn't leave tracing enabled for unrelated code such as a later benchmark |
| 392 | /// in the same process. |
| 393 | /// |
| 394 | /// The foreground journal collector is created at the same point, so |
| 395 | /// foreground work recorded before the scope starts (e.g. per-iteration |
| 396 | /// setup) is excluded from what [`Self::finish`] returns: a collector only |
| 397 | /// observes entries recorded after its creation. |
| 398 | struct TraceScope { |
| 399 | collector: FrameTimingCollector, |
| 400 | journal_collector: ForegroundJournalCollector, |
| 401 | _trace_guard: profiler::TraceGuard, |
| 402 | } |
| 403 | |
| 404 | impl TraceScope { |
| 405 | fn start(journal_collector: ForegroundJournalCollector) -> Self { |
| 406 | let trace_guard = profiler::trace_scope(); |
| 407 | Self { |
| 408 | collector: FrameTimingCollector::new(), |
| 409 | journal_collector, |
| 410 | _trace_guard: trace_guard, |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | fn finish(mut self) -> TracedEvents { |
| 415 | TracedEvents { |
| 416 | frame_events: self.collector.collect_unseen(), |
| 417 | journal_entries: self.journal_collector.collect_unseen().entries, |
| 418 | } |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | /// Events observed during one [`TraceScope`]. |
| 423 | struct TracedEvents { |
| 424 | frame_events: Vec<FrameEvent>, |
| 425 | journal_entries: Vec<ForegroundJournalEntry>, |
| 426 | } |
| 427 | |
| 428 | impl TracedEvents { |
| 429 | /// Foreground journal entries that describe completed work (task polls, |
| 430 | /// action handlers, input dispatches, draws, presents, and folded |
| 431 | /// sub-floor polls), excluding interval boundaries and metadata. |
| 432 | fn foreground_events(&self) -> impl Iterator<Item = &ForegroundEvent> { |
| 433 | self.journal_entries.iter().filter_map(|entry| match entry { |
| 434 | ForegroundJournalEntry::Event(event) => Some(event), |
| 435 | _ => None, |
| 436 | }) |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | struct MeasuredTaskInput<Input> { |
| 441 | input: Input, |
| 442 | trace_scope: Option<TraceScope>, |
| 443 | } |
| 444 | |
| 445 | struct MeasuredTaskOutput<Output> { |
| 446 | trace_scope: Option<TraceScope>, |
| 447 | report: BenchReport, |
| 448 | _output: Output, |
| 449 | } |
| 450 | |
| 451 | impl<Output> Drop for MeasuredTaskOutput<Output> { |
| 452 | fn drop(&mut self) { |
| 453 | let trace_scope = self |
| 454 | .trace_scope |
| 455 | .take() |
| 456 | .expect("measured task output should retain its trace scope"); |
| 457 | let events = trace_scope.finish(); |
| 458 | self.report.record_frame_timings(events.frame_events.iter()); |
| 459 | self.report |
| 460 | .record_foreground_events(events.foreground_events()); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | #[cfg(test)] |
| 465 | fn run_task_to_completion<Output>( |
| 466 | foreground_executor: &ForegroundExecutor, |
| 467 | task: Task<Output>, |
| 468 | ) -> Output |
| 469 | where |
| 470 | Output: 'static, |
| 471 | { |
| 472 | let output = Rc::new(RefCell::new(None)); |
| 473 | foreground_executor |
| 474 | .spawn({ |
| 475 | let output = output.clone(); |
| 476 | async move { |
| 477 | *output.borrow_mut() = Some(task.await); |
| 478 | } |
| 479 | }) |
| 480 | .detach(); |
| 481 | |
| 482 | foreground_executor |
| 483 | .dispatcher() |
| 484 | .as_threaded() |
| 485 | .expect("BenchAppContext requires a ThreadedDispatcher") |
| 486 | .run_until(|| output.borrow_mut().take()) |
| 487 | } |
| 488 | |
| 489 | /// A GPUI app context for Criterion benchmarks. |
| 490 | /// |
| 491 | /// `BenchAppContext` is intentionally separate from `TestAppContext`: it owns a |
| 492 | /// benchmark app instance and exposes only the app/window operations needed by |
| 493 | /// benchmark setup. Criterion remains responsible for the measured loop via its |
| 494 | /// `Bencher` API. |
| 495 | #[derive(Clone)] |
| 496 | pub struct BenchAppContext<'a, 'measurement> { |
| 497 | app: Rc<AppCell>, |
| 498 | background_executor: BackgroundExecutor, |
| 499 | foreground_executor: ForegroundExecutor, |
| 500 | benchmark_name: Option<&'static str>, |
| 501 | bencher: Rc<RefCell<Option<&'a mut criterion::Bencher<'measurement, BenchMeasurement>>>>, |
| 502 | report: BenchReport, |
| 503 | } |
| 504 | |
| 505 | impl<'a, 'measurement> BenchAppContext<'a, 'measurement> { |
| 506 | /// Creates a new benchmark app context backed by the provided platform. |
| 507 | /// |
| 508 | /// The platform's executors must be backed by a [`ThreadedDispatcher`] |
| 509 | /// (see [`bench_platform`]) so the context can drain foreground work via |
| 510 | /// [`Self::run_until_idle`]; panics otherwise. |
| 511 | pub fn new( |
| 512 | platform: Rc<dyn Platform>, |
| 513 | benchmark_name: Option<&'static str>, |
| 514 | bencher: &'a mut criterion::Bencher<'measurement, BenchMeasurement>, |
| 515 | ) -> Self { |
| 516 | Self::build(platform, benchmark_name, bencher, BenchReport::default()) |
| 517 | } |
| 518 | |
| 519 | /// Creates a new benchmark app context backed by the provided platform. |
| 520 | /// |
| 521 | /// The platform's executors must be backed by a [`ThreadedDispatcher`] |
| 522 | /// (see [`bench_platform`]) so the context can drain foreground work via |
| 523 | /// [`Self::run_until_idle`]; panics otherwise. |
| 524 | #[doc(hidden)] |
| 525 | pub fn new_with_platform_and_report( |
| 526 | platform: Rc<dyn Platform>, |
| 527 | benchmark_name: Option<&'static str>, |
| 528 | bencher: &'a mut criterion::Bencher<'measurement, BenchMeasurement>, |
| 529 | report: BenchReport, |
| 530 | ) -> Self { |
| 531 | Self::build(platform, benchmark_name, bencher, report) |
| 532 | } |
| 533 | |
| 534 | fn build( |
| 535 | platform: Rc<dyn Platform>, |
| 536 | benchmark_name: Option<&'static str>, |
| 537 | bencher: &'a mut criterion::Bencher<'measurement, BenchMeasurement>, |
| 538 | report: BenchReport, |
| 539 | ) -> Self { |
| 540 | let background_executor = platform.background_executor(); |
| 541 | // Validate up front so misconfiguration fails at construction with a |
| 542 | // clear message instead of deep inside `run_until_idle`. |
| 543 | assert!( |
| 544 | background_executor.dispatcher().as_threaded().is_some(), |
| 545 | "BenchAppContext requires a platform whose executors are backed by a \ |
| 546 | ThreadedDispatcher; construct one with gpui::bench_platform" |
| 547 | ); |
| 548 | let foreground_executor = platform.foreground_executor(); |
| 549 | let asset_source = Arc::new(()); |
| 550 | // Benchmark setup must not make accidental network requests. The |
| 551 | // production `BlockedHttpClient` reports them without enabling a |
| 552 | // configurable test double through `test-support`. |
| 553 | let http_client: Arc<dyn http_client::HttpClient> = |
| 554 | Arc::new(http_client::BlockedHttpClient::new()); |
| 555 | let app = App::new_app(platform, asset_source, http_client); |
| 556 | |
| 557 | Self { |
| 558 | app, |
| 559 | background_executor, |
| 560 | foreground_executor, |
| 561 | benchmark_name, |
| 562 | bencher: Rc::new(RefCell::new(Some(bencher))), |
| 563 | report, |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | /// The benchmark function name that created this context. |
| 568 | pub fn benchmark_name(&self) -> Option<&'static str> { |
| 569 | self.benchmark_name |
| 570 | } |
| 571 | |
| 572 | /// Returns the background executor used by this benchmark app. |
| 573 | pub fn background_executor(&self) -> &BackgroundExecutor { |
| 574 | &self.background_executor |
| 575 | } |
| 576 | |
| 577 | /// Returns the foreground executor used by this benchmark app. |
| 578 | pub fn foreground_executor(&self) -> &ForegroundExecutor { |
| 579 | &self.foreground_executor |
| 580 | } |
| 581 | |
| 582 | /// Updates the app and flushes synchronous GPUI effects afterward. |
| 583 | pub fn update<R>(&mut self, update: impl FnOnce(&mut App) -> R) -> R { |
| 584 | let mut app = self.app.borrow_mut(); |
| 585 | app.update(update) |
| 586 | } |
| 587 | |
| 588 | /// Reads app state. |
| 589 | pub fn read<R>(&self, read: impl FnOnce(&App) -> R) -> R { |
| 590 | let app = self.app.borrow(); |
| 591 | read(&app) |
| 592 | } |
| 593 | |
| 594 | /// Runs queued foreground tasks on this thread and waits for in flight |
| 595 | /// background work to finish. Timers that aren't due yet are not waited |
| 596 | /// for (see [`ThreadedDispatcher::run_until_idle`]). Scheduled frames are |
| 597 | /// delivered after each task poll and when there are no ready tasks, but |
| 598 | /// animations alone do not keep this method running. |
| 599 | pub fn run_until_idle(&self) { |
| 600 | let dispatcher = self |
| 601 | .background_executor |
| 602 | .dispatcher() |
| 603 | .as_threaded() |
| 604 | .expect("validated in BenchAppContext::build"); |
| 605 | dispatcher.run_until_idle_with(|| { |
| 606 | let ran_tasks = dispatcher.run_ready_main_tasks_with( |
| 607 | || true, |
| 608 | || { |
| 609 | self.dispatch_pending_frames(|| true); |
| 610 | }, |
| 611 | ); |
| 612 | if !ran_tasks { |
| 613 | self.dispatch_pending_frames(|| true); |
| 614 | } |
| 615 | ran_tasks |
| 616 | }); |
| 617 | } |
| 618 | |
| 619 | /// Alternates draining queued work with GPUI update cycles until neither |
| 620 | /// makes progress, so state dropped by benchmark code is fully released. |
| 621 | /// |
| 622 | /// Dropped entities are released only inside an update's effect flush, and |
| 623 | /// releases cascade: one flush drops the entities whose handles are gone, |
| 624 | /// their drops release further handles and can queue foreground work, and |
| 625 | /// a later flush collects those. Executor pumping alone never runs a |
| 626 | /// flush, so without this dropped state would linger in the entity map |
| 627 | /// until some woken task happened to run an update. Production gets this |
| 628 | /// cadence for free from frames and input events. |
| 629 | pub fn settle(&mut self) { |
| 630 | let dispatcher = self.background_executor.dispatcher().clone(); |
| 631 | let dispatcher = dispatcher |
| 632 | .as_threaded() |
| 633 | .expect("validated in BenchAppContext::build"); |
| 634 | loop { |
| 635 | self.run_until_idle(); |
| 636 | self.update(|_| ()); |
| 637 | self.dispatch_pending_frames(|| true); |
| 638 | if dispatcher.is_idle() { |
| 639 | return; |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | /// Runs main-thread tasks until `ready` returns a value. |
| 645 | /// |
| 646 | /// While incomplete, scheduled frames run after each task poll and while |
| 647 | /// waiting for work. Readiness is checked before frame delivery, so completion |
| 648 | /// does not wait for a final presentation; renderer sessions do that explicitly. |
| 649 | pub fn run_until<R>(&self, ready: impl FnMut() -> Option<R>) -> R { |
| 650 | self.background_executor |
| 651 | .dispatcher() |
| 652 | .as_threaded() |
| 653 | .expect("validated in BenchAppContext::build") |
| 654 | .run_until_with_frames(ready, || self.dispatch_pending_frames(|| true)) |
| 655 | } |
| 656 | |
| 657 | /// Creates a collector observing foreground journal entries recorded |
| 658 | /// from this point on, for use by a new [`TraceScope`]. |
| 659 | fn foreground_journal_collector(&self) -> ForegroundJournalCollector { |
| 660 | self.read(|app| app.foreground_journal().collector()) |
| 661 | } |
| 662 | |
| 663 | /// Measures a generic benchmark workload using Criterion's iteration loop. |
| 664 | /// |
| 665 | /// The closure is invoked once per Criterion iteration with this |
| 666 | /// benchmark app context so it can update GPUI state. Each iteration then |
| 667 | /// delivers the scheduled frame batch, without draining foreground tasks. |
| 668 | /// |
| 669 | /// Any window draws triggered by the workload are recorded into the |
| 670 | /// benchmark's frame report through the GPUI frame profiler. |
| 671 | pub fn bench_iter(&mut self, mut benchmark: impl FnMut(&mut Self)) { |
| 672 | let bencher = self.take_bencher("bench_iter"); |
| 673 | self.dispatch_pending_frames(|| true); |
| 674 | let collector = TraceScope::start(self.foreground_journal_collector()); |
| 675 | self.report.metrics.discard_pending(); |
| 676 | let mut iterations = 0; |
| 677 | let mut benchmark = || { |
| 678 | iterations += 1; |
| 679 | benchmark(self); |
| 680 | self.dispatch_pending_frames(|| true); |
| 681 | }; |
| 682 | bencher.iter(&mut benchmark); |
| 683 | let events = collector.finish(); |
| 684 | self.report.metrics.record_sample(iterations); |
| 685 | self.report.record_frame_timings(events.frame_events.iter()); |
| 686 | self.report |
| 687 | .record_foreground_events(events.foreground_events()); |
| 688 | self.replace_bencher(bencher); |
| 689 | } |
| 690 | |
| 691 | /// Measures a GPUI task to completion using Criterion's iteration loop. |
| 692 | /// |
| 693 | /// The closure is invoked once per Criterion iteration. The returned task |
| 694 | /// may depend on foreground work, background work, timers, or external |
| 695 | /// workers that wake GPUI tasks. Its output is dropped after the timed |
| 696 | /// interval. |
| 697 | /// |
| 698 | /// Any window draws triggered by the task are recorded into the benchmark's |
| 699 | /// frame report through the GPUI frame profiler. |
| 700 | pub fn bench_task<Output>(&mut self, mut benchmark: impl FnMut(&mut Self) -> Task<Output>) |
| 701 | where |
| 702 | Output: 'static, |
| 703 | { |
| 704 | self.bench_batched_task_internal("bench_task", |_| (), |_, cx| benchmark(cx)); |
| 705 | } |
| 706 | |
| 707 | /// Measures a GPUI task with per-iteration setup outside the timed interval. |
| 708 | /// |
| 709 | /// `setup` runs before timing starts. The returned input is passed by mutable |
| 710 | /// reference to `benchmark`, which returns the task whose completion is |
| 711 | /// measured. Both the setup input and task output are dropped after timing |
| 712 | /// stops. |
| 713 | /// |
| 714 | /// Each iteration is kept in its own Criterion batch so profiler tracing and |
| 715 | /// destruction cannot overlap adjacent measurements. |
| 716 | pub fn bench_batched_task<Input, Output>( |
| 717 | &mut self, |
| 718 | setup: impl FnMut(&mut Self) -> Input, |
| 719 | benchmark: impl FnMut(&mut Input, &mut Self) -> Task<Output>, |
| 720 | ) where |
| 721 | Output: 'static, |
| 722 | { |
| 723 | self.bench_batched_task_internal("bench_batched_task", setup, benchmark); |
| 724 | } |
| 725 | |
| 726 | fn bench_batched_task_internal<Input, Output>( |
| 727 | &mut self, |
| 728 | benchmark_kind: &str, |
| 729 | mut setup: impl FnMut(&mut Self) -> Input, |
| 730 | mut benchmark: impl FnMut(&mut Input, &mut Self) -> Task<Output>, |
| 731 | ) where |
| 732 | Output: 'static, |
| 733 | { |
| 734 | let bencher = self.take_bencher(benchmark_kind); |
| 735 | let mut setup_context = self.clone(); |
| 736 | let mut benchmark_context = self.clone(); |
| 737 | let foreground_executor = self.foreground_executor.clone(); |
| 738 | let report = self.report.clone(); |
| 739 | report.metrics.discard_pending(); |
| 740 | let iterations = std::cell::Cell::new(0); |
| 741 | |
| 742 | bencher.iter_batched_ref( |
| 743 | || { |
| 744 | // The previous iteration's input and output were just |
| 745 | // dropped; settling here releases their entities before the |
| 746 | // next setup, so per-iteration state cannot accumulate |
| 747 | // across a measurement. |
| 748 | setup_context.settle(); |
| 749 | let input = setup(&mut setup_context); |
| 750 | setup_context.dispatch_pending_frames(|| true); |
| 751 | MeasuredTaskInput { |
| 752 | input, |
| 753 | trace_scope: Some(TraceScope::start( |
| 754 | setup_context.foreground_journal_collector(), |
| 755 | )), |
| 756 | } |
| 757 | }, |
| 758 | |measured_input| { |
| 759 | iterations.set(iterations.get() + 1); |
| 760 | let task = benchmark(&mut measured_input.input, &mut benchmark_context); |
| 761 | benchmark_context.dispatch_pending_frames(|| true); |
| 762 | let output = Rc::new(RefCell::new(None)); |
| 763 | let completion = foreground_executor.spawn({ |
| 764 | let output = output.clone(); |
| 765 | async move { |
| 766 | *output.borrow_mut() = Some(task.await); |
| 767 | } |
| 768 | }); |
| 769 | let output = benchmark_context.run_until(|| output.borrow_mut().take()); |
| 770 | drop(completion); |
| 771 | MeasuredTaskOutput { |
| 772 | trace_scope: measured_input.trace_scope.take(), |
| 773 | report: report.clone(), |
| 774 | _output: output, |
| 775 | } |
| 776 | }, |
| 777 | criterion::BatchSize::PerIteration, |
| 778 | ); |
| 779 | report.metrics.record_sample(iterations.get()); |
| 780 | self.replace_bencher(bencher); |
| 781 | } |
| 782 | |
| 783 | /// Measures unpaced update and rendering work for an entity in its current window. |
| 784 | /// |
| 785 | /// Each iteration runs `update` against the entity in its current window. In |
| 786 | /// renderer measurements, effects flush without drawing until the platform |
| 787 | /// frame callback. The entity should be part of the window's render tree, such as the |
| 788 | /// root view or a child of it. |
| 789 | /// |
| 790 | /// Each iteration first pumps at most the initial ready task count, delivering |
| 791 | /// pending frames after every poll. It then runs `update` and delivers pending |
| 792 | /// frames again. Nested actions and effects finish before frame delivery. |
| 793 | /// This measures work and rendering cost, not display latency: there is no |
| 794 | /// pacing, and the report's frame budget does not control execution. |
| 795 | /// |
| 796 | /// Frame events are collected through the GPUI frame profiler |
| 797 | /// ([`crate::profiler::record_frame_event`]), which is enabled for the |
| 798 | /// duration of the measurement. |
| 799 | pub fn bench_renderer<V>( |
| 800 | &mut self, |
| 801 | view: Entity<V>, |
| 802 | mut update: impl FnMut(&mut V, &mut Window, &mut Context<V>), |
| 803 | ) where |
| 804 | V: 'static + Render, |
| 805 | { |
| 806 | let bencher = self.take_bencher("bench_renderer"); |
| 807 | let dispatcher = self.background_executor.dispatcher().clone(); |
| 808 | self.dispatch_pending_frames(|| true); |
| 809 | let collector = TraceScope::start(self.foreground_journal_collector()); |
| 810 | self.report.metrics.discard_pending(); |
| 811 | let mut iterations = 0; |
| 812 | let mut benchmark = || { |
| 813 | iterations += 1; |
| 814 | dispatcher |
| 815 | .as_threaded() |
| 816 | .expect("validated in BenchAppContext::build") |
| 817 | .run_ready_main_tasks_with( |
| 818 | || true, |
| 819 | || { |
| 820 | self.dispatch_pending_frames(|| true); |
| 821 | }, |
| 822 | ); |
| 823 | self.with_window(view.entity_id(), |window, cx| { |
| 824 | view.update(cx, |view, cx| update(view, window, cx)); |
| 825 | }) |
| 826 | .expect("cannot benchmark renderer for entity without a current window"); |
| 827 | self.dispatch_pending_frames(|| true); |
| 828 | }; |
| 829 | bencher.iter(&mut benchmark); |
| 830 | |
| 831 | let events = collector.finish(); |
| 832 | self.report.metrics.record_sample(iterations); |
| 833 | self.report.record_frame_timings(events.frame_events.iter()); |
| 834 | self.report |
| 835 | .record_foreground_events(events.foreground_events()); |
| 836 | self.replace_bencher(bencher); |
| 837 | } |
| 838 | |
| 839 | /// Measures finite rendering sessions with fresh, untimed setup for each iteration. |
| 840 | /// |
| 841 | /// `setup` returns session state, its window, and a shared stop flag. |
| 842 | /// Loop turns pump at most the initial ready foreground task count, then call |
| 843 | /// `input` with a zero-based turn number unless stopped. Pending frames are |
| 844 | /// delivered after each task poll and input callback. Between polls, the stop |
| 845 | /// flag and session deadline are checked. The ready batch snapshots a count, |
| 846 | /// not task identities; rendering after a poll does not inject another input. |
| 847 | /// This is an unpaced work-and-render policy, not OS event-loop emulation. |
| 848 | /// Once stopped, only scheduled platform frame callbacks run until the window |
| 849 | /// is clean and its final changes have been submitted for presentation. |
| 850 | /// Pending animation callbacks alone do not delay completion. |
| 851 | /// Turns run without pacing or explicit OS-thread yields. A clean turn need not draw. |
| 852 | /// |
| 853 | /// Store `true` with release ordering to stop. Stopping does not imply success: |
| 854 | /// validate the workload in `Input::drop` or retained fixture state afterward. |
| 855 | /// Setup, session state destruction, and report aggregation are outside both |
| 856 | /// timing and tracing. Own outstanding tasks in `Input` so dropping it cancels |
| 857 | /// them; do not detach session work that could leak into subsequent iterations. |
| 858 | /// |
| 859 | /// # Panics |
| 860 | /// |
| 861 | /// Panics if the window is removed or stopping and final presentation exceed `timeout`. |
| 862 | /// The deadline is checked between polls and frames and cannot preempt a blocking task |
| 863 | /// poll, input callback, draw, or present. |
| 864 | pub fn bench_renderer_session<Input>( |
| 865 | &mut self, |
| 866 | timeout: Duration, |
| 867 | mut setup: impl FnMut(&mut Self) -> (Input, AnyWindowHandle, Arc<AtomicBool>), |
| 868 | mut input: impl FnMut(&mut Input, u64, &mut Window, &mut App), |
| 869 | ) { |
| 870 | let bencher = self.take_bencher("bench_renderer_session"); |
| 871 | let mut setup_context = self.clone(); |
| 872 | let mut benchmark_context = self.clone(); |
| 873 | let dispatcher = self.background_executor.dispatcher().clone(); |
| 874 | let dispatcher = dispatcher |
| 875 | .as_threaded() |
| 876 | .expect("validated in BenchAppContext::build"); |
| 877 | let report = self.report.clone(); |
| 878 | report.metrics.discard_pending(); |
| 879 | let iterations = std::cell::Cell::new(0); |
| 880 | |
| 881 | bencher.iter_batched_ref( |
| 882 | || { |
| 883 | setup_context.settle(); |
| 884 | let input = setup(&mut setup_context); |
| 885 | setup_context.dispatch_pending_frames(|| true); |
| 886 | MeasuredTaskInput { |
| 887 | input, |
| 888 | trace_scope: Some(TraceScope::start( |
| 889 | setup_context.foreground_journal_collector(), |
| 890 | )), |
| 891 | } |
| 892 | }, |
| 893 | |measured_input| { |
| 894 | iterations.set(iterations.get() + 1); |
| 895 | let (state, window, stopped) = &mut measured_input.input; |
| 896 | let started = Instant::now(); |
| 897 | let check_deadline = || { |
| 898 | assert!( |
| 899 | started.elapsed() < timeout, |
| 900 | "renderer session did not stop within {timeout:?} with final changes presented" |
| 901 | ); |
| 902 | }; |
| 903 | let can_poll = || { |
| 904 | check_deadline(); |
| 905 | !stopped.load(Ordering::Acquire) |
| 906 | }; |
| 907 | let is_finished = |cx: &Self| { |
| 908 | if !stopped.load(Ordering::Acquire) { |
| 909 | return false; |
| 910 | } |
| 911 | // Animation callbacks alone must not keep a stopped session alive. |
| 912 | let app = cx.app.borrow(); |
| 913 | let window = app |
| 914 | .windows |
| 915 | .get(window.window_id()) |
| 916 | .and_then(Option::as_deref) |
| 917 | .expect("renderer session window must remain open"); |
| 918 | !window.invalidator.is_dirty() && !window.needs_present.get() |
| 919 | }; |
| 920 | let dispatch_frames = |cx: &Self| { |
| 921 | check_deadline(); |
| 922 | cx.dispatch_pending_frames(|| { |
| 923 | check_deadline(); |
| 924 | !is_finished(cx) |
| 925 | }); |
| 926 | check_deadline(); |
| 927 | }; |
| 928 | let mut frame = 0; |
| 929 | loop { |
| 930 | check_deadline(); |
| 931 | if is_finished(&benchmark_context) { |
| 932 | break; |
| 933 | } |
| 934 | if can_poll() { |
| 935 | dispatcher.run_ready_main_tasks_with(&can_poll, || { |
| 936 | dispatch_frames(&benchmark_context); |
| 937 | }); |
| 938 | if !can_poll() { |
| 939 | continue; |
| 940 | } |
| 941 | benchmark_context |
| 942 | .update_window(*window, |_, window, cx| { |
| 943 | if can_poll() { |
| 944 | input(state, frame, window, cx); |
| 945 | } |
| 946 | }) |
| 947 | .expect("renderer session window must remain open"); |
| 948 | } |
| 949 | dispatch_frames(&benchmark_context); |
| 950 | frame += 1; |
| 951 | } |
| 952 | MeasuredTaskOutput { |
| 953 | trace_scope: measured_input.trace_scope.take(), |
| 954 | report: report.clone(), |
| 955 | _output: (), |
| 956 | } |
| 957 | }, |
| 958 | criterion::BatchSize::PerIteration, |
| 959 | ); |
| 960 | report.metrics.record_sample(iterations.get()); |
| 961 | self.replace_bencher(bencher); |
| 962 | } |
| 963 | |
| 964 | fn dispatch_pending_frames(&self, mut should_continue: impl FnMut() -> bool) -> bool { |
| 965 | let pending: Vec<_> = { |
| 966 | let mut app = self.app.borrow_mut(); |
| 967 | app.windows |
| 968 | .values_mut() |
| 969 | .filter_map(|window| { |
| 970 | let window = window.as_deref_mut()?; |
| 971 | let handle = window.window_handle(); |
| 972 | let platform_window = window |
| 973 | .platform_window |
| 974 | .as_test() |
| 975 | .expect("benchmark platform window"); |
| 976 | platform_window |
| 977 | .frame_scheduled() |
| 978 | .then(|| (handle, platform_window.clone())) |
| 979 | }) |
| 980 | .collect() |
| 981 | }; |
| 982 | |
| 983 | let mut dispatched = false; |
| 984 | for (handle, window) in pending { |
| 985 | if !should_continue() { |
| 986 | break; |
| 987 | } |
| 988 | // An earlier callback may have closed another window in the batch. |
| 989 | let is_open = self |
| 990 | .app |
| 991 | .borrow() |
| 992 | .windows |
| 993 | .get(handle.window_id()) |
| 994 | .and_then(Option::as_deref) |
| 995 | .is_some(); |
| 996 | if is_open { |
| 997 | dispatched |= window.simulate_scheduled_frame(); |
| 998 | } |
| 999 | } |
| 1000 | dispatched |
| 1001 | } |
| 1002 | |
| 1003 | /// Adds an active window with an empty root view for benchmark setup. |
| 1004 | /// |
| 1005 | /// Activation is settled before returning so renderer measurements exercise |
| 1006 | /// foreground animation rather than the inactive-window frame throttle. |
| 1007 | pub fn add_empty_window(&mut self) -> BenchWindowContext<'a, 'measurement> { |
| 1008 | let bounds = { |
| 1009 | let app = self.app.borrow(); |
| 1010 | Bounds::maximized(None, &app) |
| 1011 | }; |
| 1012 | let window = { |
| 1013 | let mut app = self.app.borrow_mut(); |
| 1014 | let window: AnyWindowHandle = app |
| 1015 | .open_window( |
| 1016 | WindowOptions { |
| 1017 | window_bounds: Some(WindowBounds::Windowed(bounds)), |
| 1018 | ..Default::default() |
| 1019 | }, |
| 1020 | |_, cx| cx.new(|_| Empty), |
| 1021 | ) |
| 1022 | .expect("failed to open benchmark window") |
| 1023 | .into(); |
| 1024 | // An active renderer workload must not inherit the platform |
| 1025 | // callback's inactive-window animation throttle. |
| 1026 | app.update_window(window, |_, window, _| window.activate_window()) |
| 1027 | .expect("failed to activate newly created benchmark window"); |
| 1028 | window |
| 1029 | }; |
| 1030 | |
| 1031 | self.run_until_idle(); |
| 1032 | BenchWindowContext { |
| 1033 | cx: self.clone(), |
| 1034 | window, |
| 1035 | } |
| 1036 | } |
| 1037 | |
| 1038 | fn take_bencher( |
| 1039 | &self, |
| 1040 | benchmark_kind: &str, |
| 1041 | ) -> &'a mut criterion::Bencher<'measurement, BenchMeasurement> { |
| 1042 | self.bencher.borrow_mut().take().unwrap_or_else(|| { |
| 1043 | panic!("cannot start {benchmark_kind}: benchmark measurement is already running") |
| 1044 | }) |
| 1045 | } |
| 1046 | |
| 1047 | fn replace_bencher(&self, bencher: &'a mut criterion::Bencher<'measurement, BenchMeasurement>) { |
| 1048 | let previous = self.bencher.borrow_mut().replace(bencher); |
| 1049 | assert!( |
| 1050 | previous.is_none(), |
| 1051 | "benchmark bencher was unexpectedly present after measurement" |
| 1052 | ); |
| 1053 | } |
| 1054 | |
| 1055 | /// Runs GPUI benchmark teardown. |
| 1056 | /// |
| 1057 | /// Cancels any timers still armed on the shared dispatcher and drains the |
| 1058 | /// work that cancellation unblocks so they can't fire during a later |
| 1059 | /// benchmark; assumes no other `BenchAppContext` is live on this thread. |
| 1060 | pub fn teardown(mut self) { |
| 1061 | self.run_until_idle(); |
| 1062 | self.update(|cx| { |
| 1063 | cx.quit(); |
| 1064 | }); |
| 1065 | self.run_until_idle(); |
| 1066 | |
| 1067 | let dispatcher = self.background_executor.dispatcher(); |
| 1068 | let dispatcher = dispatcher |
| 1069 | .as_threaded() |
| 1070 | .expect("validated in BenchAppContext::build"); |
| 1071 | |
| 1072 | drop(self.app); |
| 1073 | drop(self.foreground_executor); |
| 1074 | |
| 1075 | for _ in 0..100 { |
| 1076 | if dispatcher.cancel_pending_timers() == 0 { |
| 1077 | return; |
| 1078 | } |
| 1079 | dispatcher.run_until_idle(); |
| 1080 | } |
| 1081 | panic!( |
| 1082 | "benchmark teardown kept scheduling timers: {}", |
| 1083 | dispatcher.debug_state() |
| 1084 | ); |
| 1085 | } |
| 1086 | } |
| 1087 | |
| 1088 | impl AppContext for BenchAppContext<'_, '_> { |
| 1089 | fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> { |
| 1090 | let mut app = self.app.borrow_mut(); |
| 1091 | app.new(build_entity) |
| 1092 | } |
| 1093 | |
| 1094 | fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> { |
| 1095 | let mut app = self.app.borrow_mut(); |
| 1096 | app.reserve_entity() |
| 1097 | } |
| 1098 | |
| 1099 | fn insert_entity<T: 'static>( |
| 1100 | &mut self, |
| 1101 | reservation: Reservation<T>, |
| 1102 | build_entity: impl FnOnce(&mut Context<T>) -> T, |
| 1103 | ) -> Entity<T> { |
| 1104 | let mut app = self.app.borrow_mut(); |
| 1105 | app.insert_entity(reservation, build_entity) |
| 1106 | } |
| 1107 | |
| 1108 | fn update_entity<T: 'static, R>( |
| 1109 | &mut self, |
| 1110 | handle: &Entity<T>, |
| 1111 | update: impl FnOnce(&mut T, &mut Context<T>) -> R, |
| 1112 | ) -> R { |
| 1113 | let mut app = self.app.borrow_mut(); |
| 1114 | app.update_entity(handle, update) |
| 1115 | } |
| 1116 | |
| 1117 | fn as_mut<'b, T>(&'b mut self, _: &Entity<T>) -> GpuiBorrow<'b, T> |
| 1118 | where |
| 1119 | T: 'static, |
| 1120 | { |
| 1121 | panic!("Cannot use as_mut with BenchAppContext. Call update() instead.") |
| 1122 | } |
| 1123 | |
| 1124 | fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R |
| 1125 | where |
| 1126 | T: 'static, |
| 1127 | { |
| 1128 | let app = self.app.borrow(); |
| 1129 | app.read_entity(handle, read) |
| 1130 | } |
| 1131 | |
| 1132 | fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T> |
| 1133 | where |
| 1134 | F: FnOnce(AnyView, &mut Window, &mut App) -> T, |
| 1135 | { |
| 1136 | let mut app = self.app.borrow_mut(); |
| 1137 | app.update_window(window, update) |
| 1138 | } |
| 1139 | |
| 1140 | fn with_window<R>( |
| 1141 | &mut self, |
| 1142 | entity_id: EntityId, |
| 1143 | update: impl FnOnce(&mut Window, &mut App) -> R, |
| 1144 | ) -> Option<R> { |
| 1145 | let mut app = self.app.borrow_mut(); |
| 1146 | app.with_window(entity_id, update) |
| 1147 | } |
| 1148 | |
| 1149 | fn read_window<T, R>( |
| 1150 | &self, |
| 1151 | window: &WindowHandle<T>, |
| 1152 | read: impl FnOnce(Entity<T>, &App) -> R, |
| 1153 | ) -> Result<R> |
| 1154 | where |
| 1155 | T: 'static, |
| 1156 | { |
| 1157 | let app = self.app.borrow(); |
| 1158 | app.read_window(window, read) |
| 1159 | } |
| 1160 | |
| 1161 | fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R> |
| 1162 | where |
| 1163 | R: Send + 'static, |
| 1164 | { |
| 1165 | self.background_executor.spawn(future) |
| 1166 | } |
| 1167 | |
| 1168 | fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R |
| 1169 | where |
| 1170 | G: Global, |
| 1171 | { |
| 1172 | let app = self.app.borrow(); |
| 1173 | app.read_global(callback) |
| 1174 | } |
| 1175 | } |
| 1176 | |
| 1177 | /// A window-specific context for GPUI benchmarks. |
| 1178 | /// |
| 1179 | /// This is separate from `VisualTestContext`; it provides access to a benchmark |
| 1180 | /// window without exposing test-only helpers such as input simulation. |
| 1181 | #[derive(Clone)] |
| 1182 | pub struct BenchWindowContext<'a, 'measurement> { |
| 1183 | cx: BenchAppContext<'a, 'measurement>, |
| 1184 | window: AnyWindowHandle, |
| 1185 | } |
| 1186 | |
| 1187 | impl<'a, 'measurement> BenchWindowContext<'a, 'measurement> { |
| 1188 | /// Returns the underlying benchmark app context. |
| 1189 | pub fn app_context(&mut self) -> &mut BenchAppContext<'a, 'measurement> { |
| 1190 | &mut self.cx |
| 1191 | } |
| 1192 | |
| 1193 | /// Returns the window associated with this context. |
| 1194 | pub fn window_handle(&self) -> AnyWindowHandle { |
| 1195 | self.window |
| 1196 | } |
| 1197 | |
| 1198 | /// Runs queued foreground tasks on this thread and waits for in-flight |
| 1199 | /// background work to finish. Pending timers are not waited for. |
| 1200 | pub fn run_until_idle(&self) { |
| 1201 | self.cx.run_until_idle(); |
| 1202 | } |
| 1203 | |
| 1204 | /// Updates the benchmark window. |
| 1205 | pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> R { |
| 1206 | self.cx |
| 1207 | .update_window(self.window, |_, window, cx| update(window, cx)) |
| 1208 | .expect("benchmark window was unexpectedly closed") |
| 1209 | } |
| 1210 | } |
| 1211 | |
| 1212 | impl AppContext for BenchWindowContext<'_, '_> { |
| 1213 | fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> { |
| 1214 | self.window |
| 1215 | .update(&mut self.cx, |_, _, cx| cx.new(build_entity)) |
| 1216 | .expect("benchmark window was unexpectedly closed") |
| 1217 | } |
| 1218 | |
| 1219 | fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> { |
| 1220 | self.cx.reserve_entity() |
| 1221 | } |
| 1222 | |
| 1223 | fn insert_entity<T: 'static>( |
| 1224 | &mut self, |
| 1225 | reservation: Reservation<T>, |
| 1226 | build_entity: impl FnOnce(&mut Context<T>) -> T, |
| 1227 | ) -> Entity<T> { |
| 1228 | self.window |
| 1229 | .update(&mut self.cx, |_, _, cx| { |
| 1230 | cx.insert_entity(reservation, build_entity) |
| 1231 | }) |
| 1232 | .expect("benchmark window was unexpectedly closed") |
| 1233 | } |
| 1234 | |
| 1235 | fn update_entity<T: 'static, R>( |
| 1236 | &mut self, |
| 1237 | handle: &Entity<T>, |
| 1238 | update: impl FnOnce(&mut T, &mut Context<T>) -> R, |
| 1239 | ) -> R { |
| 1240 | self.cx.update_entity(handle, update) |
| 1241 | } |
| 1242 | |
| 1243 | fn as_mut<'b, T>(&'b mut self, handle: &Entity<T>) -> GpuiBorrow<'b, T> |
| 1244 | where |
| 1245 | T: 'static, |
| 1246 | { |
| 1247 | self.cx.as_mut(handle) |
| 1248 | } |
| 1249 | |
| 1250 | fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R |
| 1251 | where |
| 1252 | T: 'static, |
| 1253 | { |
| 1254 | self.cx.read_entity(handle, read) |
| 1255 | } |
| 1256 | |
| 1257 | fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T> |
| 1258 | where |
| 1259 | F: FnOnce(AnyView, &mut Window, &mut App) -> T, |
| 1260 | { |
| 1261 | self.cx.update_window(window, update) |
| 1262 | } |
| 1263 | |
| 1264 | fn with_window<R>( |
| 1265 | &mut self, |
| 1266 | entity_id: EntityId, |
| 1267 | update: impl FnOnce(&mut Window, &mut App) -> R, |
| 1268 | ) -> Option<R> { |
| 1269 | self.cx.with_window(entity_id, update) |
| 1270 | } |
| 1271 | |
| 1272 | fn read_window<T, R>( |
| 1273 | &self, |
| 1274 | window: &WindowHandle<T>, |
| 1275 | read: impl FnOnce(Entity<T>, &App) -> R, |
| 1276 | ) -> Result<R> |
| 1277 | where |
| 1278 | T: 'static, |
| 1279 | { |
| 1280 | self.cx.read_window(window, read) |
| 1281 | } |
| 1282 | |
| 1283 | fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R> |
| 1284 | where |
| 1285 | R: Send + 'static, |
| 1286 | { |
| 1287 | self.cx.background_spawn(future) |
| 1288 | } |
| 1289 | |
| 1290 | fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R |
| 1291 | where |
| 1292 | G: Global, |
| 1293 | { |
| 1294 | self.cx.read_global(callback) |
| 1295 | } |
| 1296 | } |
| 1297 | |
| 1298 | impl VisualContext for BenchWindowContext<'_, '_> { |
| 1299 | type Result<T> = Result<T>; |
| 1300 | |
| 1301 | fn window_handle(&self) -> AnyWindowHandle { |
| 1302 | self.window |
| 1303 | } |
| 1304 | |
| 1305 | fn update_window_entity<T: 'static, R>( |
| 1306 | &mut self, |
| 1307 | entity: &Entity<T>, |
| 1308 | update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R, |
| 1309 | ) -> Result<R> { |
| 1310 | let entity = entity.clone(); |
| 1311 | self.cx |
| 1312 | .app |
| 1313 | .borrow_mut() |
| 1314 | .with_window(entity.entity_id(), |window, app| { |
| 1315 | entity.update(app, |entity, cx| update(entity, window, cx)) |
| 1316 | }) |
| 1317 | .ok_or_else(|| { |
| 1318 | anyhow!("entity has no current window; use `update` instead of `update_in`") |
| 1319 | }) |
| 1320 | } |
| 1321 | |
| 1322 | fn new_window_entity<T: 'static>( |
| 1323 | &mut self, |
| 1324 | build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T, |
| 1325 | ) -> Result<Entity<T>> { |
| 1326 | self.window.update(&mut self.cx, |_, window, cx| { |
| 1327 | cx.new(|cx| build_entity(window, cx)) |
| 1328 | }) |
| 1329 | } |
| 1330 | |
| 1331 | fn replace_root_view<V>( |
| 1332 | &mut self, |
| 1333 | build_view: impl FnOnce(&mut Window, &mut Context<V>) -> V, |
| 1334 | ) -> Result<Entity<V>> |
| 1335 | where |
| 1336 | V: 'static + Render, |
| 1337 | { |
| 1338 | self.window.update(&mut self.cx, |_, window, cx| { |
| 1339 | window.replace_root(cx, build_view) |
| 1340 | }) |
| 1341 | } |
| 1342 | |
| 1343 | fn focus<V>(&mut self, entity: &Entity<V>) -> Result<()> |
| 1344 | where |
| 1345 | V: Focusable, |
| 1346 | { |
| 1347 | self.window.update(&mut self.cx, |_, window, cx| { |
| 1348 | entity.read(cx).focus_handle(cx).focus(window, cx) |
| 1349 | }) |
| 1350 | } |
| 1351 | } |
| 1352 | |
| 1353 | #[cfg(test)] |
| 1354 | mod tests { |
| 1355 | use std::{ |
| 1356 | rc::Rc, |
| 1357 | sync::{ |
| 1358 | Arc, |
| 1359 | atomic::{AtomicU64, Ordering}, |
| 1360 | }, |
| 1361 | }; |
| 1362 | |
| 1363 | use super::*; |
| 1364 | use crate::profiler::journal::install_test_foreground_journal; |
| 1365 | |
| 1366 | /// Runs `benchmark` under a wall-time primary with a fake counter as the |
| 1367 | /// secondary metric and returns the per-iteration values the report |
| 1368 | /// recorded for it. |
| 1369 | fn secondary_values_per_iteration( |
| 1370 | counter: Arc<AtomicU64>, |
| 1371 | benchmark: impl Fn(&mut BenchAppContext, &Arc<AtomicU64>), |
| 1372 | ) -> Vec<u64> { |
| 1373 | let platform = bench_platform(None, Arc::new(crate::NoopTextSystem::new())); |
| 1374 | let report = BenchReport::default(); |
| 1375 | let mut criterion = criterion::Criterion::default() |
| 1376 | .with_measurement( |
| 1377 | BenchMeasurement::new(criterion::measurement::WallTime).with_secondary( |
| 1378 | "fake counter", |
| 1379 | bench_metrics::FakeCounter::new(counter.clone()), |
| 1380 | ), |
| 1381 | ) |
| 1382 | .without_plots() |
| 1383 | .sample_size(10) |
| 1384 | .warm_up_time(Duration::from_millis(1)) |
| 1385 | .measurement_time(Duration::from_millis(1)); |
| 1386 | |
| 1387 | criterion.bench_function("secondary_values_per_iteration", |bencher| { |
| 1388 | let mut cx = BenchAppContext::new_with_platform_and_report( |
| 1389 | platform.clone(), |
| 1390 | Some("secondary_values_per_iteration"), |
| 1391 | bencher, |
| 1392 | report.clone(), |
| 1393 | ); |
| 1394 | // Fixture work outside the measured loop must not be attributed |
| 1395 | // to any iteration. |
| 1396 | counter.fetch_add(1_000_000, Ordering::SeqCst); |
| 1397 | benchmark(&mut cx, &counter); |
| 1398 | cx.teardown(); |
| 1399 | }); |
| 1400 | |
| 1401 | report |
| 1402 | .metrics() |
| 1403 | .values("fake counter") |
| 1404 | .expect("the fake counter was recorded") |
| 1405 | .into_iter() |
| 1406 | .map(|value| value as u64) |
| 1407 | .collect() |
| 1408 | } |
| 1409 | |
| 1410 | #[test] |
| 1411 | fn secondary_metric_is_normalized_per_iteration_for_bench_iter() { |
| 1412 | let values = secondary_values_per_iteration(Arc::new(AtomicU64::new(0)), |cx, counter| { |
| 1413 | cx.bench_iter(|_| { |
| 1414 | counter.fetch_add(11, Ordering::SeqCst); |
| 1415 | }); |
| 1416 | }); |
| 1417 | assert!(!values.is_empty()); |
| 1418 | assert!( |
| 1419 | values.iter().all(|value| *value == 11), |
| 1420 | "each sample's total should be divided by its iteration count: {values:?}" |
| 1421 | ); |
| 1422 | } |
| 1423 | |
| 1424 | #[test] |
| 1425 | fn secondary_metric_is_accumulated_across_per_iteration_batches() { |
| 1426 | let values = secondary_values_per_iteration(Arc::new(AtomicU64::new(0)), |cx, counter| { |
| 1427 | cx.bench_batched_task( |
| 1428 | |_| { |
| 1429 | // Setup runs outside every measured interval. |
| 1430 | counter.fetch_add(1_000, Ordering::SeqCst); |
| 1431 | }, |
| 1432 | |(), cx| { |
| 1433 | counter.fetch_add(11, Ordering::SeqCst); |
| 1434 | cx.background_spawn(async {}) |
| 1435 | }, |
| 1436 | ); |
| 1437 | }); |
| 1438 | assert!(!values.is_empty()); |
| 1439 | assert!( |
| 1440 | values.iter().all(|value| *value == 11), |
| 1441 | "PerIteration batches should sum to one per-iteration value: {values:?}" |
| 1442 | ); |
| 1443 | } |
| 1444 | |
| 1445 | #[test] |
| 1446 | fn foreground_work_reports_long_task_without_window_draw() { |
| 1447 | let (journal, _journal_guard) = install_test_foreground_journal(1024, 64); |
| 1448 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 1449 | let foreground_executor = ForegroundExecutor::new(dispatcher); |
| 1450 | |
| 1451 | let trace_scope = TraceScope::start(journal.collector()); |
| 1452 | |
| 1453 | // A single foreground task poll that never touches a window, akin |
| 1454 | // to the stall a debounced background computation can cause. |
| 1455 | let task = foreground_executor.spawn(async move { |
| 1456 | std::thread::sleep(Duration::from_millis(60)); |
| 1457 | }); |
| 1458 | run_task_to_completion(&foreground_executor, task); |
| 1459 | |
| 1460 | let events = trace_scope.finish(); |
| 1461 | assert!( |
| 1462 | events.frame_events.is_empty(), |
| 1463 | "no window was involved, so no frame events should be recorded" |
| 1464 | ); |
| 1465 | |
| 1466 | let report = BenchReport::default(); |
| 1467 | report.record_foreground_events(events.foreground_events()); |
| 1468 | |
| 1469 | let summary = report |
| 1470 | .foreground_work() |
| 1471 | .expect("a long task poll should be reported even without a window draw"); |
| 1472 | // The spawned task's own poll is one sample; the tiny wrapper poll |
| 1473 | // that observes its completion in `run_task_to_completion` folds |
| 1474 | // into a second, near-zero sample rather than being dropped. |
| 1475 | assert!(summary.count >= 1, "expected at least one recorded item"); |
| 1476 | assert!( |
| 1477 | summary.max >= Duration::from_millis(55), |
| 1478 | "expected the long poll's duration to be recorded, got {:?}", |
| 1479 | summary.max |
| 1480 | ); |
| 1481 | // `total` is an exact sum, while `max` may be rounded up to its |
| 1482 | // histogram bucket's boundary, so compare each against the expected |
| 1483 | // floor directly instead of against each other. |
| 1484 | assert!( |
| 1485 | summary.total >= Duration::from_millis(55), |
| 1486 | "expected the long poll's duration to be included in the total, got {:?}", |
| 1487 | summary.total |
| 1488 | ); |
| 1489 | } |
| 1490 | |
| 1491 | #[test] |
| 1492 | fn foreground_work_excludes_setup_before_trace_scope_starts() { |
| 1493 | let (journal, _journal_guard) = install_test_foreground_journal(1024, 64); |
| 1494 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 1495 | let foreground_executor = ForegroundExecutor::new(dispatcher); |
| 1496 | |
| 1497 | // Fixture/setup work that must not be attributed to the measurement: |
| 1498 | // a long poll recorded before the trace scope (and its journal |
| 1499 | // collector) is created. |
| 1500 | let setup_task = foreground_executor.spawn(async move { |
| 1501 | std::thread::sleep(Duration::from_millis(80)); |
| 1502 | }); |
| 1503 | run_task_to_completion(&foreground_executor, setup_task); |
| 1504 | |
| 1505 | let trace_scope = TraceScope::start(journal.collector()); |
| 1506 | |
| 1507 | let measured_task = foreground_executor.spawn(async move { |
| 1508 | std::thread::sleep(Duration::from_millis(10)); |
| 1509 | }); |
| 1510 | run_task_to_completion(&foreground_executor, measured_task); |
| 1511 | |
| 1512 | let events = trace_scope.finish(); |
| 1513 | let report = BenchReport::default(); |
| 1514 | report.record_foreground_events(events.foreground_events()); |
| 1515 | |
| 1516 | let summary = report |
| 1517 | .foreground_work() |
| 1518 | .expect("the measured task's poll should be reported"); |
| 1519 | assert!( |
| 1520 | summary.max < Duration::from_millis(40), |
| 1521 | "setup work's 80ms poll must not leak into the measured summary, got {:?}", |
| 1522 | summary.max |
| 1523 | ); |
| 1524 | assert!( |
| 1525 | summary.total < Duration::from_millis(40), |
| 1526 | "setup work's 80ms poll must not leak into the measured total, got {:?}", |
| 1527 | summary.total |
| 1528 | ); |
| 1529 | } |
| 1530 | |
| 1531 | #[test] |
| 1532 | fn bench_task_reports_long_task_without_window() { |
| 1533 | let platform = bench_platform(None, Arc::new(crate::NoopTextSystem::new())); |
| 1534 | let report = BenchReport::default(); |
| 1535 | let name = "bench_task_reports_long_task_without_window"; |
| 1536 | |
| 1537 | let mut criterion = criterion::Criterion::default() |
| 1538 | .with_measurement(BenchMeasurement::new(criterion::measurement::WallTime)) |
| 1539 | .without_plots() |
| 1540 | .sample_size(10) |
| 1541 | .warm_up_time(Duration::from_millis(1)) |
| 1542 | .measurement_time(Duration::from_millis(1)); |
| 1543 | |
| 1544 | criterion.bench_function(name, |bencher| { |
| 1545 | let mut cx = BenchAppContext::new_with_platform_and_report( |
| 1546 | platform.clone(), |
| 1547 | Some(name), |
| 1548 | bencher, |
| 1549 | report.clone(), |
| 1550 | ); |
| 1551 | cx.bench_task(|cx| { |
| 1552 | cx.foreground_executor().spawn(async move { |
| 1553 | std::thread::sleep(Duration::from_millis(20)); |
| 1554 | }) |
| 1555 | }); |
| 1556 | cx.teardown(); |
| 1557 | }); |
| 1558 | |
| 1559 | let summary = report |
| 1560 | .foreground_work() |
| 1561 | .expect("bench_task should report foreground work with no window involved"); |
| 1562 | assert!( |
| 1563 | summary.max >= Duration::from_millis(15), |
| 1564 | "expected a ~20ms task poll to be recorded, got {:?}", |
| 1565 | summary.max |
| 1566 | ); |
| 1567 | } |
| 1568 | |
| 1569 | #[test] |
| 1570 | fn task_completion_supports_non_send_foreground_output() { |
| 1571 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 1572 | let background_executor = BackgroundExecutor::new(dispatcher.clone()); |
| 1573 | let foreground_executor = ForegroundExecutor::new(dispatcher); |
| 1574 | let (sender, receiver) = futures::channel::oneshot::channel(); |
| 1575 | |
| 1576 | background_executor |
| 1577 | .spawn(async move { |
| 1578 | sender |
| 1579 | .send(()) |
| 1580 | .expect("foreground receiver should remain alive"); |
| 1581 | }) |
| 1582 | .detach(); |
| 1583 | let expected_output = Rc::new(42); |
| 1584 | let task_output = expected_output.clone(); |
| 1585 | let task = foreground_executor.spawn(async move { |
| 1586 | receiver.await.expect("background task should send a value"); |
| 1587 | task_output |
| 1588 | }); |
| 1589 | |
| 1590 | let output = run_task_to_completion(&foreground_executor, task); |
| 1591 | assert!( |
| 1592 | Rc::ptr_eq(&output, &expected_output), |
| 1593 | "task runner should preserve non-Send foreground output" |
| 1594 | ); |
| 1595 | } |
| 1596 | } |