.cargo/
crates/
brain/
diff/
benches/
highlight.rs
11.3 KiB
render.rs
28.7 KiB
src/
tests/
Cargo.toml
867 B
README.md
696 B
files/
highlight/
repo/
signals/
tui/
tui-core/
tui-termion/
tui-widgets/
scripts/
src/
.gitignore
30 B
.gitsigners
198 B
AGENTS.md
1.9 KiB
CONTRIBUTING
1.7 KiB
Cargo.lock
5.4 KiB
Cargo.toml
1.9 KiB
LICENSE
1.1 KiB
README.md
245 B
STYLE
3.7 KiB
clippy.toml
213 B
crates/diff/benches/render.rs
raw
| 1 | //! Render benchmarks for `rustik-diff`. |
| 2 | //! |
| 3 | //! The benchmark decodes deterministic unified diffs once, then exercises |
| 4 | //! render, scroll, resize, focus, highlight-request, and highlight-refresh paths. |
| 5 | |
| 6 | use std::hint::black_box; |
| 7 | use std::io::{self, Write as _}; |
| 8 | use std::str::FromStr; |
| 9 | use std::time::{Duration, Instant}; |
| 10 | |
| 11 | use rustik_diff::{ |
| 12 | BuiltinHighlighter, Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer, |
| 13 | HighlightRequest, HighlightResult, |
| 14 | }; |
| 15 | use rustik_highlight as syntax; |
| 16 | use rustik_tui::{ |
| 17 | Buffer, Color, Constraint, Label, Line, Rect, Scroll, Style, Table, TableOptions, |
| 18 | }; |
| 19 | |
| 20 | /// Fixed terminal-sized render area. |
| 21 | const AREA: Rect = Rect::new(0, 0, 120, 40); |
| 22 | /// Narrow terminal area used by resize-heavy scenarios. |
| 23 | const NARROW_AREA: Rect = Rect::new(0, 0, 80, 24); |
| 24 | /// Wide terminal area used by resize-heavy scenarios. |
| 25 | const WIDE_AREA: Rect = Rect::new(0, 0, 180, 50); |
| 26 | /// Tiny terminal area used to stress minimum-width rendering. |
| 27 | const TINY_AREA: Rect = Rect::new(0, 0, 44, 12); |
| 28 | /// Default frame count. |
| 29 | const DEFAULT_FRAMES: usize = 80; |
| 30 | /// Default frame count for expensive real syntax-highlight landing runs. |
| 31 | const DEFAULT_HIGHLIGHT_FRAMES: usize = 3; |
| 32 | /// Default frame count for each workload in the full suite. |
| 33 | const DEFAULT_SUITE_FRAMES: usize = DEFAULT_FRAMES; |
| 34 | /// Default number of independent timed runs per workload. |
| 35 | const DEFAULT_RUNS: usize = 3; |
| 36 | /// Default number of file sections in the generated diff. |
| 37 | const DEFAULT_FILES: usize = 32; |
| 38 | /// Default number of hunk lines per generated file. |
| 39 | const DEFAULT_LINES: usize = 128; |
| 40 | /// One row sample stride for the checksum. |
| 41 | const SAMPLE_ROWS: usize = 5; |
| 42 | /// One column sample stride for the checksum. |
| 43 | const SAMPLE_COLS: usize = 7; |
| 44 | /// Low-emphasis report text color. |
| 45 | const REPORT_DIM: Color = Color::Fixed(244); |
| 46 | /// Theme name used by the interactive pager. |
| 47 | const THEME_NAME: &str = "rustik-catppuccin-mocha"; |
| 48 | /// Built-in syntax theme JSON used by the interactive pager. |
| 49 | const THEME: &str = include_str!("../src/themes/rustik-catppuccin-mocha.json"); |
| 50 | |
| 51 | /// Runs the benchmark. |
| 52 | fn main() { |
| 53 | let args = Args::parse(); |
| 54 | let workloads = args.workload.expanded(); |
| 55 | let report_widths = ReportWidths::new(&workloads); |
| 56 | let mut checksum = 0usize; |
| 57 | |
| 58 | for workload in workloads { |
| 59 | let report = run_workload(workload, args); |
| 60 | checksum ^= report.checksum.rotate_left(report.workload as u32); |
| 61 | report_workload(&report, report_widths); |
| 62 | black_box(report); |
| 63 | } |
| 64 | black_box(checksum); |
| 65 | } |
| 66 | |
| 67 | /// Benchmark command-line arguments. |
| 68 | #[derive(Clone, Copy, Debug)] |
| 69 | struct Args { |
| 70 | /// Workload to run. |
| 71 | workload: Workload, |
| 72 | /// Number of frames to render. |
| 73 | frames: FrameCount, |
| 74 | /// Number of independent timed runs per workload. |
| 75 | runs: usize, |
| 76 | /// Number of synthetic file sections. |
| 77 | files: usize, |
| 78 | /// Number of synthetic hunk lines per file. |
| 79 | lines: usize, |
| 80 | } |
| 81 | |
| 82 | impl Args { |
| 83 | /// Parses benchmark arguments from the process environment. |
| 84 | fn parse() -> Self { |
| 85 | Self::parse_from(std::env::args().skip(1)) |
| 86 | } |
| 87 | |
| 88 | /// Parses benchmark arguments from an iterator. |
| 89 | fn parse_from(args: impl IntoIterator<Item = String>) -> Self { |
| 90 | let mut parsed = Self { |
| 91 | workload: Workload::All, |
| 92 | frames: FrameCount::Default, |
| 93 | runs: DEFAULT_RUNS, |
| 94 | files: DEFAULT_FILES, |
| 95 | lines: DEFAULT_LINES, |
| 96 | }; |
| 97 | let mut args = args.into_iter(); |
| 98 | |
| 99 | while let Some(arg) = args.next() { |
| 100 | match arg.as_str() { |
| 101 | "--workload" | "-w" => parsed.workload = next_workload(&mut args, parsed.workload), |
| 102 | "--frames" => { |
| 103 | parsed.frames = FrameCount::Explicit(next_usize(&mut args, DEFAULT_FRAMES)); |
| 104 | } |
| 105 | "--runs" => parsed.runs = next_usize(&mut args, parsed.runs).max(1), |
| 106 | "--files" => parsed.files = next_usize(&mut args, parsed.files), |
| 107 | "--lines" => parsed.lines = next_usize(&mut args, parsed.lines), |
| 108 | "--help" | "-h" => { |
| 109 | println!( |
| 110 | "usage: cargo bench -p rustik-diff --bench render -- [--workload NAME] [--runs N] [--frames N] [--files N] [--lines N]" |
| 111 | ); |
| 112 | std::process::exit(0); |
| 113 | } |
| 114 | value => { |
| 115 | if let Ok(value) = value.parse() { |
| 116 | parsed.frames = FrameCount::Explicit(value); |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | parsed |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /// Frame-count selection mode. |
| 127 | #[derive(Clone, Copy, Debug)] |
| 128 | enum FrameCount { |
| 129 | /// Use workload-sensitive defaults. |
| 130 | Default, |
| 131 | /// Use the same explicit frame count for every selected workload. |
| 132 | Explicit(usize), |
| 133 | } |
| 134 | |
| 135 | impl FrameCount { |
| 136 | /// Returns the concrete frame count for one workload. |
| 137 | const fn for_workload(self, requested: Workload) -> usize { |
| 138 | match (self, requested) { |
| 139 | (Self::Default, Workload::Highlight) => DEFAULT_HIGHLIGHT_FRAMES, |
| 140 | (Self::Default, Workload::All) => DEFAULT_SUITE_FRAMES, |
| 141 | (Self::Default, _) => DEFAULT_FRAMES, |
| 142 | (Self::Explicit(frames), _) => frames, |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | /// Named benchmark workload. |
| 148 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 149 | enum Workload { |
| 150 | /// Original fixed-area, warm-cache, one-line scroll workload. |
| 151 | WarmScroll, |
| 152 | /// Mixed pager session with scrolling, navigation, and resize. |
| 153 | Session, |
| 154 | /// Width-changing render workload. |
| 155 | Resize, |
| 156 | /// Scrolling offsets concentrated around file boundaries. |
| 157 | Sticky, |
| 158 | /// Visible syntax-highlight landing workload. |
| 159 | Highlight, |
| 160 | /// Visible highlight request scheduling without drawing rows. |
| 161 | HighlightRequests, |
| 162 | /// Steady-state render of word-diff overlays on a warm highlight cache. |
| 163 | WordDiff, |
| 164 | /// Large file-count workload with short hunks. |
| 165 | ManyFiles, |
| 166 | /// Single huge file workload. |
| 167 | HugeFile, |
| 168 | /// Long and Unicode-heavy source line workload. |
| 169 | LongLines, |
| 170 | /// Runs every named workload. |
| 171 | All, |
| 172 | } |
| 173 | |
| 174 | impl Workload { |
| 175 | /// Returns concrete workloads represented by this value. |
| 176 | fn expanded(self) -> Vec<Self> { |
| 177 | match self { |
| 178 | Self::All => vec![ |
| 179 | Self::WarmScroll, |
| 180 | Self::Session, |
| 181 | Self::Resize, |
| 182 | Self::Sticky, |
| 183 | Self::Highlight, |
| 184 | Self::HighlightRequests, |
| 185 | Self::WordDiff, |
| 186 | Self::ManyFiles, |
| 187 | Self::HugeFile, |
| 188 | Self::LongLines, |
| 189 | ], |
| 190 | workload => vec![workload], |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | /// Returns the workload display name. |
| 195 | const fn name(self) -> &'static str { |
| 196 | match self { |
| 197 | Self::WarmScroll => "warm-scroll", |
| 198 | Self::Session => "session", |
| 199 | Self::Resize => "resize", |
| 200 | Self::Sticky => "sticky", |
| 201 | Self::Highlight => "highlight", |
| 202 | Self::HighlightRequests => "highlight-requests", |
| 203 | Self::WordDiff => "word-diff", |
| 204 | Self::ManyFiles => "many-files", |
| 205 | Self::HugeFile => "huge-file", |
| 206 | Self::LongLines => "long-lines", |
| 207 | Self::All => "all", |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | /// Returns the report unit measured by the workload. |
| 212 | const fn metric_unit(self) -> &'static str { |
| 213 | match self { |
| 214 | Self::HighlightRequests => "tps", |
| 215 | Self::Highlight => "ms/land", |
| 216 | Self::WarmScroll |
| 217 | | Self::Session |
| 218 | | Self::Resize |
| 219 | | Self::Sticky |
| 220 | | Self::WordDiff |
| 221 | | Self::ManyFiles |
| 222 | | Self::HugeFile |
| 223 | | Self::LongLines |
| 224 | | Self::All => "fps", |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | /// Converts an elapsed workload run into the reported metric. |
| 229 | fn metric_value(self, elapsed: Duration, frames: usize) -> f64 { |
| 230 | let frames = frames.max(1); |
| 231 | match self { |
| 232 | Self::Highlight => elapsed.as_secs_f64() * 1_000.0 / frames as f64, |
| 233 | _ => frames as f64 / elapsed.as_secs_f64(), |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | /// Returns the synthetic document shape for the workload. |
| 238 | fn document_shape(self, args: Args) -> DiffShape { |
| 239 | match self { |
| 240 | Self::ManyFiles => DiffShape { |
| 241 | files: args.files.max(1_024), |
| 242 | lines: 12, |
| 243 | hunk_lines: 6, |
| 244 | profile: LineProfile::Tiny, |
| 245 | }, |
| 246 | Self::HugeFile => DiffShape { |
| 247 | files: 1, |
| 248 | lines: args.lines.max(16_384), |
| 249 | hunk_lines: 256, |
| 250 | profile: LineProfile::Normal, |
| 251 | }, |
| 252 | Self::LongLines => DiffShape { |
| 253 | files: args.files, |
| 254 | lines: args.lines, |
| 255 | hunk_lines: 64, |
| 256 | profile: LineProfile::LongUnicode, |
| 257 | }, |
| 258 | Self::Highlight => { |
| 259 | let lines = args.lines.max(16_384); |
| 260 | DiffShape { |
| 261 | files: 1, |
| 262 | lines, |
| 263 | hunk_lines: lines, |
| 264 | profile: LineProfile::Normal, |
| 265 | } |
| 266 | } |
| 267 | Self::Sticky => DiffShape { |
| 268 | files: args.files.max(256), |
| 269 | lines: 32, |
| 270 | hunk_lines: 16, |
| 271 | profile: LineProfile::Normal, |
| 272 | }, |
| 273 | Self::Session |
| 274 | | Self::Resize |
| 275 | | Self::HighlightRequests |
| 276 | | Self::WordDiff |
| 277 | | Self::WarmScroll |
| 278 | | Self::All => DiffShape { |
| 279 | files: args.files, |
| 280 | lines: args.lines, |
| 281 | hunk_lines: 64, |
| 282 | profile: LineProfile::Normal, |
| 283 | }, |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | impl FromStr for Workload { |
| 289 | type Err = (); |
| 290 | |
| 291 | fn from_str(value: &str) -> Result<Self, Self::Err> { |
| 292 | match value { |
| 293 | "warm-scroll" | "plain" | "scroll" => Ok(Self::WarmScroll), |
| 294 | "session" => Ok(Self::Session), |
| 295 | "resize" => Ok(Self::Resize), |
| 296 | "sticky" | "sticky-boundaries" => Ok(Self::Sticky), |
| 297 | "highlight" | "highlights" => Ok(Self::Highlight), |
| 298 | "highlight-requests" | "requests" => Ok(Self::HighlightRequests), |
| 299 | "word-diff" | "worddiff" => Ok(Self::WordDiff), |
| 300 | "many-files" => Ok(Self::ManyFiles), |
| 301 | "huge-file" => Ok(Self::HugeFile), |
| 302 | "long-lines" => Ok(Self::LongLines), |
| 303 | "all" => Ok(Self::All), |
| 304 | _ => Err(()), |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | /// Shape of a generated diff document. |
| 310 | #[derive(Clone, Copy, Debug)] |
| 311 | struct DiffShape { |
| 312 | /// Number of files to generate. |
| 313 | files: usize, |
| 314 | /// Number of source rows to generate per file. |
| 315 | lines: usize, |
| 316 | /// Maximum number of rows per hunk. |
| 317 | hunk_lines: usize, |
| 318 | /// Source-line content profile. |
| 319 | profile: LineProfile, |
| 320 | } |
| 321 | |
| 322 | /// Source-line text profile. |
| 323 | #[derive(Clone, Copy, Debug)] |
| 324 | enum LineProfile { |
| 325 | /// Short Rust-like lines. |
| 326 | Normal, |
| 327 | /// Very small hunks for many-file workloads. |
| 328 | Tiny, |
| 329 | /// Wide rows with Unicode graphemes. |
| 330 | LongUnicode, |
| 331 | } |
| 332 | |
| 333 | /// Result from one workload run. |
| 334 | #[derive(Clone, Copy, Debug)] |
| 335 | struct BenchReport { |
| 336 | /// Workload that produced the report. |
| 337 | workload: Workload, |
| 338 | /// Workload metric statistics across independent runs. |
| 339 | metric: RepeatStats, |
| 340 | /// Combined deterministic render checksum across independent runs. |
| 341 | checksum: usize, |
| 342 | } |
| 343 | |
| 344 | /// Summary statistics for repeated benchmark runs. |
| 345 | #[derive(Clone, Copy, Debug)] |
| 346 | struct RepeatStats { |
| 347 | /// Average reported workload value. |
| 348 | avg: f64, |
| 349 | /// Reported workload value standard deviation. |
| 350 | stddev: f64, |
| 351 | } |
| 352 | |
| 353 | /// Report column widths derived before workloads run. |
| 354 | #[derive(Clone, Copy, Debug)] |
| 355 | struct ReportWidths { |
| 356 | /// Widest selected workload name. |
| 357 | workload: usize, |
| 358 | /// Width reserved for formatted workload metrics. |
| 359 | metric: usize, |
| 360 | } |
| 361 | |
| 362 | /// Widest expected workload-metric value used to keep streaming rows aligned. |
| 363 | const METRIC_FORMAT: &str = "000000.0"; |
| 364 | |
| 365 | /// Parses the next argument as a `usize`. |
| 366 | fn next_usize(args: &mut impl Iterator<Item = String>, fallback: usize) -> usize { |
| 367 | args.next() |
| 368 | .and_then(|value| value.parse().ok()) |
| 369 | .unwrap_or(fallback) |
| 370 | } |
| 371 | |
| 372 | /// Parses the next argument as a workload. |
| 373 | fn next_workload(args: &mut impl Iterator<Item = String>, fallback: Workload) -> Workload { |
| 374 | args.next() |
| 375 | .and_then(|value| value.parse().ok()) |
| 376 | .unwrap_or(fallback) |
| 377 | } |
| 378 | |
| 379 | /// Runs one named benchmark workload. |
| 380 | fn run_workload(workload: Workload, args: Args) -> BenchReport { |
| 381 | let frames = args.frames.for_workload(workload); |
| 382 | let shape = workload.document_shape(args); |
| 383 | let input = synthetic_diff(shape); |
| 384 | let document = match DiffDocument::decode_str(&input) { |
| 385 | Ok(document) => document, |
| 386 | Err(error) => { |
| 387 | eprintln!("failed to decode generated benchmark diff: {error}"); |
| 388 | std::process::exit(1); |
| 389 | } |
| 390 | }; |
| 391 | let rows = rustik_tui::Widget::size( |
| 392 | &DiffViewer::new(document.clone(), DiffOptions::default()), |
| 393 | Constraint::UNBOUNDED, |
| 394 | ) |
| 395 | .rows; |
| 396 | let mut metrics = Vec::with_capacity(args.runs); |
| 397 | let mut checksum = rows; |
| 398 | |
| 399 | for run in 0..args.runs { |
| 400 | let (run_elapsed, run_checksum) = run_once(workload, document.clone(), frames); |
| 401 | metrics.push(workload.metric_value(run_elapsed, frames)); |
| 402 | checksum ^= run_checksum.rotate_left((run % usize::BITS as usize) as u32); |
| 403 | } |
| 404 | |
| 405 | BenchReport { |
| 406 | workload, |
| 407 | metric: RepeatStats::from_values(&metrics), |
| 408 | checksum, |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | /// Runs one independent timed pass for a workload. |
| 413 | fn run_once(workload: Workload, document: DiffDocument, frames: usize) -> (Duration, usize) { |
| 414 | match workload { |
| 415 | Workload::WarmScroll => run_warm_scroll(document, frames), |
| 416 | Workload::Session => run_session(document, frames), |
| 417 | Workload::Resize => run_resize(document, frames), |
| 418 | Workload::Sticky => run_sticky(document, frames), |
| 419 | Workload::Highlight => run_highlight(document, frames), |
| 420 | Workload::HighlightRequests => run_highlight_requests(document, frames), |
| 421 | Workload::WordDiff => run_word_diff(document, frames), |
| 422 | Workload::ManyFiles => run_session(document, frames), |
| 423 | Workload::HugeFile => run_sticky(document, frames), |
| 424 | Workload::LongLines => run_resize(document, frames), |
| 425 | Workload::All => unreachable!("run_once: all is expanded before dispatch"), |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | /// Renders a fixed-area warm-cache scrolling workload. |
| 430 | fn run_warm_scroll(document: DiffDocument, frames: usize) -> (Duration, usize) { |
| 431 | let mut viewer = DiffViewer::new(document, DiffOptions::default()); |
| 432 | let mut buffer = Buffer::empty(AREA); |
| 433 | let start = Instant::now(); |
| 434 | let mut checksum = 0usize; |
| 435 | |
| 436 | for frame in 0..frames { |
| 437 | buffer.clear(); |
| 438 | viewer.render(AREA, &mut buffer); |
| 439 | checksum ^= sample_buffer(&buffer, frame); |
| 440 | viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA); |
| 441 | buffer.reset_dirty(); |
| 442 | } |
| 443 | |
| 444 | (start.elapsed(), checksum) |
| 445 | } |
| 446 | |
| 447 | /// Renders a mixed pager session. |
| 448 | fn run_session(document: DiffDocument, frames: usize) -> (Duration, usize) { |
| 449 | let areas = [AREA, AREA, WIDE_AREA, AREA, NARROW_AREA, AREA]; |
| 450 | run_scripted(document, frames, |viewer, frame| { |
| 451 | let area = areas[frame % areas.len()]; |
| 452 | match frame % 24 { |
| 453 | 0 => apply_resize(viewer, area), |
| 454 | 1..=6 => { |
| 455 | viewer.apply(DiffAction::Scroll(Scroll::Lines(3)), area); |
| 456 | } |
| 457 | 7 => { |
| 458 | viewer.apply( |
| 459 | DiffAction::Scroll(Scroll::Lines((area.rows / 2) as isize)), |
| 460 | area, |
| 461 | ); |
| 462 | } |
| 463 | 8 => { |
| 464 | viewer.apply(DiffAction::NextHunk, area); |
| 465 | } |
| 466 | 9 => { |
| 467 | viewer.apply(DiffAction::FocusNext, area); |
| 468 | } |
| 469 | 10 => { |
| 470 | viewer.apply(DiffAction::FocusPrevious, area); |
| 471 | } |
| 472 | 11 => { |
| 473 | viewer.apply(DiffAction::NextHunk, area); |
| 474 | } |
| 475 | 12 => { |
| 476 | viewer.apply(DiffAction::PreviousHunk, area); |
| 477 | } |
| 478 | _ => { |
| 479 | viewer.apply(DiffAction::Scroll(Scroll::Lines(-1)), area); |
| 480 | } |
| 481 | } |
| 482 | area |
| 483 | }) |
| 484 | } |
| 485 | |
| 486 | /// Renders while invalidating width-dependent caches with resize events. |
| 487 | fn run_resize(document: DiffDocument, frames: usize) -> (Duration, usize) { |
| 488 | let areas = [AREA, WIDE_AREA, NARROW_AREA, TINY_AREA, AREA]; |
| 489 | run_scripted(document, frames, |viewer, frame| { |
| 490 | let area = areas[frame % areas.len()]; |
| 491 | apply_resize(viewer, area); |
| 492 | viewer.apply( |
| 493 | DiffAction::Scroll(Scroll::Lines((frame % 7) as isize - 3)), |
| 494 | area, |
| 495 | ); |
| 496 | area |
| 497 | }) |
| 498 | } |
| 499 | |
| 500 | /// Renders offsets concentrated around sticky file-header transitions. |
| 501 | fn run_sticky(document: DiffDocument, frames: usize) -> (Duration, usize) { |
| 502 | run_scripted(document, frames, |viewer, frame| { |
| 503 | if frame % 16 == 0 { |
| 504 | viewer.apply(DiffAction::FocusNext, AREA); |
| 505 | } else if frame % 16 < 8 { |
| 506 | viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA); |
| 507 | } else { |
| 508 | viewer.apply(DiffAction::Scroll(Scroll::Lines(-1)), AREA); |
| 509 | } |
| 510 | AREA |
| 511 | }) |
| 512 | } |
| 513 | |
| 514 | /// Renders until visible rows have real syntax highlights applied. |
| 515 | fn run_highlight(document: DiffDocument, frames: usize) -> (Duration, usize) { |
| 516 | let mut viewer = DiffViewer::new(document, DiffOptions::default()); |
| 517 | let mut buffer = Buffer::empty(AREA); |
| 518 | let rows = rustik_tui::Widget::size(&viewer, Constraint::UNBOUNDED).rows; |
| 519 | viewer.apply(DiffAction::Scroll(Scroll::Lines((rows / 2) as isize)), AREA); |
| 520 | let start = Instant::now(); |
| 521 | let raw_theme = match THEME.parse::<syntax::RawTheme>() { |
| 522 | Ok(theme) => theme, |
| 523 | Err(error) => { |
| 524 | eprintln!("failed to parse benchmark theme: {error:?}"); |
| 525 | std::process::exit(1); |
| 526 | } |
| 527 | }; |
| 528 | let mut raw = match syntax::syntaxes::RUST.parse::<syntax::RawGrammar>() { |
| 529 | Ok(raw) => raw, |
| 530 | Err(error) => { |
| 531 | eprintln!("failed to parse benchmark grammar: {error:?}"); |
| 532 | std::process::exit(1); |
| 533 | } |
| 534 | }; |
| 535 | if !raw |
| 536 | .file_types |
| 537 | .iter() |
| 538 | .any(|existing| existing.eq_ignore_ascii_case("rs")) |
| 539 | { |
| 540 | raw.file_types.push("rs".to_owned()); |
| 541 | } |
| 542 | let rust_grammar = match syntax::Grammar::compile_with(&raw, &[]) { |
| 543 | Ok(grammar) => grammar, |
| 544 | Err(error) => { |
| 545 | eprintln!("failed to compile benchmark grammar: {error:?}"); |
| 546 | std::process::exit(1); |
| 547 | } |
| 548 | }; |
| 549 | let mut registry = syntax::Registry::default(); |
| 550 | registry.add_theme(syntax::Theme::compile(&raw_theme)); |
| 551 | registry.add_grammar(rust_grammar); |
| 552 | let mut highlighter = BuiltinHighlighter::new(registry, THEME_NAME); |
| 553 | let mut checksum = 0usize; |
| 554 | |
| 555 | for frame in 0..frames { |
| 556 | buffer.clear(); |
| 557 | viewer.render(AREA, &mut buffer); |
| 558 | checksum ^= sample_buffer(&buffer, frame); |
| 559 | let requests = viewer.visible_highlight_requests(AREA); |
| 560 | let results = highlighter.highlight_requests(requests); |
| 561 | viewer.apply_highlights(results); |
| 562 | buffer.clear(); |
| 563 | viewer.render(AREA, &mut buffer); |
| 564 | checksum ^= sample_buffer(&buffer, frame.wrapping_add(frames)); |
| 565 | viewer.apply( |
| 566 | DiffAction::Scroll(Scroll::Lines((frame % 5 + 1) as isize)), |
| 567 | AREA, |
| 568 | ); |
| 569 | buffer.reset_dirty(); |
| 570 | } |
| 571 | |
| 572 | (start.elapsed(), checksum) |
| 573 | } |
| 574 | |
| 575 | /// Renders cached word-diff overlays with a warm highlight cache. |
| 576 | /// |
| 577 | /// Pre-applies synthetic highlight results for the rows the workload will |
| 578 | /// scroll across, then measures render+scroll cost on already-overlaid lines. |
| 579 | /// Because every `-/+` pair in `synthetic_diff` passes the word-diff similarity |
| 580 | /// gate, this isolates the cached-render fast path that |
| 581 | /// [`DiffViewer::apply_highlights`] now bakes the overlay into. |
| 582 | fn run_word_diff(document: DiffDocument, frames: usize) -> (Duration, usize) { |
| 583 | let mut viewer = DiffViewer::new(document, DiffOptions::default()); |
| 584 | let mut buffer = Buffer::empty(AREA); |
| 585 | let span = AREA.rows.saturating_mul(2) as isize; |
| 586 | |
| 587 | // Walk forward across the scroll span so every row we'll visit gets a |
| 588 | // highlight result. Then walk back to the start before timing begins. |
| 589 | for _ in 0..span { |
| 590 | let requests = viewer.highlight_requests(AREA); |
| 591 | viewer.apply_highlights(requests.into_iter().map(highlight_result)); |
| 592 | viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA); |
| 593 | } |
| 594 | viewer.apply(DiffAction::Scroll(Scroll::Lines(-span)), AREA); |
| 595 | |
| 596 | let start = Instant::now(); |
| 597 | let mut checksum = 0usize; |
| 598 | |
| 599 | for frame in 0..frames { |
| 600 | buffer.clear(); |
| 601 | viewer.render(AREA, &mut buffer); |
| 602 | checksum ^= sample_buffer(&buffer, frame); |
| 603 | let step = if (frame as isize / span) % 2 == 0 { |
| 604 | 1 |
| 605 | } else { |
| 606 | -1 |
| 607 | }; |
| 608 | viewer.apply(DiffAction::Scroll(Scroll::Lines(step)), AREA); |
| 609 | buffer.reset_dirty(); |
| 610 | } |
| 611 | (start.elapsed(), checksum) |
| 612 | } |
| 613 | |
| 614 | /// Schedules visible highlight requests without drawing rendered rows. |
| 615 | fn run_highlight_requests(document: DiffDocument, frames: usize) -> (Duration, usize) { |
| 616 | let mut viewer = DiffViewer::new(document, DiffOptions::default()); |
| 617 | let start = Instant::now(); |
| 618 | let mut checksum = 0usize; |
| 619 | |
| 620 | for frame in 0..frames { |
| 621 | let requests = viewer.highlight_requests(AREA); |
| 622 | checksum ^= sample_requests(&requests, frame); |
| 623 | viewer.apply( |
| 624 | DiffAction::Scroll(Scroll::Lines((frame % 5 + 1) as isize)), |
| 625 | AREA, |
| 626 | ); |
| 627 | } |
| 628 | |
| 629 | (start.elapsed(), checksum) |
| 630 | } |
| 631 | |
| 632 | /// Renders frames using a caller-provided action script. |
| 633 | fn run_scripted( |
| 634 | document: DiffDocument, |
| 635 | frames: usize, |
| 636 | mut script: impl FnMut(&mut DiffViewer, usize) -> Rect, |
| 637 | ) -> (Duration, usize) { |
| 638 | let mut viewer = DiffViewer::new(document, DiffOptions::default()); |
| 639 | let mut buffer = Buffer::empty(AREA); |
| 640 | let start = Instant::now(); |
| 641 | let mut checksum = 0usize; |
| 642 | |
| 643 | for frame in 0..frames { |
| 644 | let area = script(&mut viewer, frame); |
| 645 | buffer.resize(area); |
| 646 | buffer.clear(); |
| 647 | viewer.render(area, &mut buffer); |
| 648 | checksum ^= sample_buffer(&buffer, frame); |
| 649 | buffer.reset_dirty(); |
| 650 | } |
| 651 | |
| 652 | (start.elapsed(), checksum) |
| 653 | } |
| 654 | |
| 655 | /// Applies resize handling for an area. |
| 656 | fn apply_resize(viewer: &mut DiffViewer, area: Rect) { |
| 657 | viewer.apply(DiffAction::Resize, area); |
| 658 | } |
| 659 | |
| 660 | /// Converts a highlight request into a deterministic synthetic result. |
| 661 | fn highlight_result(request: HighlightRequest) -> HighlightResult { |
| 662 | let line = Line::new( |
| 663 | Label::from( |
| 664 | request |
| 665 | .source |
| 666 | .line(request.key.source_line) |
| 667 | .unwrap_or_default(), |
| 668 | ) |
| 669 | .fg(Color::Yellow), |
| 670 | ); |
| 671 | HighlightResult::new(request, line) |
| 672 | } |
| 673 | |
| 674 | /// Creates a deterministic Git-style unified diff. |
| 675 | fn synthetic_diff(shape: DiffShape) -> String { |
| 676 | let mut diff = String::new(); |
| 677 | |
| 678 | for file in 0..shape.files { |
| 679 | diff.push_str(&format!( |
| 680 | "diff --git a/src/file_{file:04}.rs b/src/file_{file:04}.rs\n" |
| 681 | )); |
| 682 | diff.push_str(&format!("index {file:040x}..{:040x} 100644\n", file + 1)); |
| 683 | diff.push_str(&format!("--- a/src/file_{file:04}.rs\n")); |
| 684 | diff.push_str(&format!("+++ b/src/file_{file:04}.rs\n")); |
| 685 | |
| 686 | let mut old_start = 1usize; |
| 687 | let mut new_start = 1usize; |
| 688 | for hunk_start in (0..shape.lines).step_by(shape.hunk_lines.max(1)) { |
| 689 | let hunk_lines = shape.hunk_lines.min(shape.lines - hunk_start); |
| 690 | let hunk_range = hunk_start..hunk_start + hunk_lines; |
| 691 | let additions = hunk_range.clone().filter(|line| line % 5 == 1).count(); |
| 692 | let deletions = hunk_range.filter(|line| line % 5 == 0).count(); |
| 693 | let context = hunk_lines.saturating_sub(additions + deletions); |
| 694 | let old_lines = deletions + context; |
| 695 | let new_lines = additions + context; |
| 696 | |
| 697 | diff.push_str(&format!( |
| 698 | "@@ -{old_start},{old_lines} +{new_start},{new_lines} @@ fn file_{file:04}_hunk_{hunk_start:04}()\n" |
| 699 | )); |
| 700 | |
| 701 | for line in hunk_start..hunk_start + hunk_lines { |
| 702 | push_diff_line(&mut diff, shape.profile, file, line); |
| 703 | } |
| 704 | |
| 705 | old_start += old_lines + 8; |
| 706 | new_start += new_lines + 8; |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | diff |
| 711 | } |
| 712 | |
| 713 | /// Adds one generated diff line. |
| 714 | fn push_diff_line(diff: &mut String, profile: LineProfile, file: usize, line: usize) { |
| 715 | let prefix = match line % 5 { |
| 716 | 0 => '-', |
| 717 | 1 => '+', |
| 718 | _ => ' ', |
| 719 | }; |
| 720 | diff.push(prefix); |
| 721 | diff.push_str(&line_text(profile, file, line)); |
| 722 | diff.push('\n'); |
| 723 | } |
| 724 | |
| 725 | /// Returns one generated source line. |
| 726 | fn line_text(profile: LineProfile, file: usize, line: usize) -> String { |
| 727 | match profile { |
| 728 | LineProfile::Normal => match line % 5 { |
| 729 | 0 => format!("let old_value_{line:04} = compute({file}, {line});"), |
| 730 | 1 => format!("let new_value_{line:04} = compute_fast({file}, {line});"), |
| 731 | _ => format!("let stable_value_{line:04} = keep({file}, {line});"), |
| 732 | }, |
| 733 | LineProfile::Tiny => format!("v{file}_{line}();"), |
| 734 | LineProfile::LongUnicode => format!( |
| 735 | "let sample_{line:04} = \"file={file} row={line} λ ❤️ {}\";", |
| 736 | "payload_segment::".repeat(line % 19 + 12) |
| 737 | ), |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | /// Samples a buffer for a deterministic checksum. |
| 742 | fn sample_buffer(buffer: &Buffer, frame: usize) -> usize { |
| 743 | let area = buffer.area(); |
| 744 | let mut checksum = frame; |
| 745 | |
| 746 | for row in (0..area.rows).step_by(SAMPLE_ROWS) { |
| 747 | for col in (0..area.cols).step_by(SAMPLE_COLS) { |
| 748 | if let Some(cell) = buffer.get(area.x + col, area.y + row) { |
| 749 | checksum = checksum.wrapping_mul(16_777_619) ^ cell.glyph().len(); |
| 750 | checksum ^= color_id(cell.style().fg_color()); |
| 751 | checksum ^= color_id(cell.style().bg_color()).rotate_left(7); |
| 752 | } |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | checksum |
| 757 | } |
| 758 | |
| 759 | /// Samples highlight requests for a deterministic checksum. |
| 760 | fn sample_requests(requests: &[HighlightRequest], frame: usize) -> usize { |
| 761 | requests |
| 762 | .iter() |
| 763 | .fold(frame ^ requests.len(), |checksum, request| { |
| 764 | checksum |
| 765 | ^ request.key.text_hash as usize |
| 766 | ^ request.source.text.len() |
| 767 | ^ request |
| 768 | .path |
| 769 | .as_ref() |
| 770 | .map_or(0, |path| path.as_os_str().len()) |
| 771 | }) |
| 772 | } |
| 773 | |
| 774 | /// Returns a stable numeric id for a color. |
| 775 | fn color_id(color: Color) -> usize { |
| 776 | match color { |
| 777 | Color::Unset => 0, |
| 778 | Color::Black => 1, |
| 779 | Color::Red => 2, |
| 780 | Color::Green => 3, |
| 781 | Color::Yellow => 4, |
| 782 | Color::Blue => 5, |
| 783 | Color::Magenta => 6, |
| 784 | Color::Cyan => 7, |
| 785 | Color::White => 8, |
| 786 | Color::Fixed(value) => 0x100 + usize::from(value), |
| 787 | Color::RGB(r, g, b) => { |
| 788 | 0x1_0000 + (usize::from(r) << 16) + (usize::from(g) << 8) + usize::from(b) |
| 789 | } |
| 790 | } |
| 791 | } |
| 792 | |
| 793 | /// Prints one styled workload report line. |
| 794 | fn report_workload(report: &BenchReport, widths: ReportWidths) { |
| 795 | let table = Table::new(TableOptions { |
| 796 | spacing: 3, |
| 797 | ..TableOptions::default() |
| 798 | }) |
| 799 | .row([ |
| 800 | Label::from("x".repeat(widths.workload)), |
| 801 | Label::from("0".repeat(widths.metric)), |
| 802 | Label::from(format!("±{}", "0".repeat(widths.metric))), |
| 803 | ]) |
| 804 | .row([ |
| 805 | Label::new(report.workload.name()).style(Style::default().bold()), |
| 806 | Label::from(format_metric( |
| 807 | report.metric.avg, |
| 808 | report.workload.metric_unit(), |
| 809 | )) |
| 810 | .fg(Color::White), |
| 811 | Label::from(format!("±{:.1}", report.metric.stddev)).fg(REPORT_DIM), |
| 812 | ]); |
| 813 | |
| 814 | if let Some(line) = table.lines(Constraint::UNBOUNDED).get(1) { |
| 815 | println!("{}", line.styled()); |
| 816 | } |
| 817 | flush_stdout(); |
| 818 | } |
| 819 | |
| 820 | impl ReportWidths { |
| 821 | /// Computes report column widths for a selected workload set. |
| 822 | fn new(workloads: &[Workload]) -> Self { |
| 823 | Self { |
| 824 | workload: workloads |
| 825 | .iter() |
| 826 | .map(|workload| workload.name().len()) |
| 827 | .max() |
| 828 | .unwrap_or_default(), |
| 829 | metric: workloads |
| 830 | .iter() |
| 831 | .map(|workload| METRIC_FORMAT.len() + 1 + workload.metric_unit().len()) |
| 832 | .max() |
| 833 | .unwrap_or(METRIC_FORMAT.len() + 1 + "fps".len()), |
| 834 | } |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | /// Flushes benchmark output after an incremental report. |
| 839 | fn flush_stdout() { |
| 840 | let _ = io::stdout().flush(); |
| 841 | } |
| 842 | |
| 843 | impl RepeatStats { |
| 844 | /// Computes statistics from repeated numeric values. |
| 845 | fn from_values(values: &[f64]) -> Self { |
| 846 | let count = values.len() as f64; |
| 847 | let avg = values.iter().sum::<f64>() / count; |
| 848 | let variance = values |
| 849 | .iter() |
| 850 | .map(|value| { |
| 851 | let delta = value - avg; |
| 852 | delta * delta |
| 853 | }) |
| 854 | .sum::<f64>() |
| 855 | / count; |
| 856 | |
| 857 | Self { |
| 858 | avg, |
| 859 | stddev: variance.sqrt(), |
| 860 | } |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | /// Formats a workload report metric. |
| 865 | fn format_metric(value: f64, unit: &str) -> String { |
| 866 | format!("{value:.1} {unit}") |
| 867 | } |