diff: Add render benchmark

7c1e02d6dcb1cbd5f0db3a5af5fe5498330b169b
Adds a synthetic rustik-diff render workload for measuring viewer performance.
Alexis Sellier committed ago 1 parent 8274aafc
crates/diff/Cargo.toml +4 -0
10 10
[dependencies]
11 11
rustik-highlight.workspace = true
12 12
rustik-tui = { workspace = true, features = ["widgets"] }
13 13
rustik-tui-termion.workspace = true
14 14
15 +
[[bench]]
16 +
name = "render"
17 +
harness = false
18 +
15 19
[lints]
16 20
workspace = true
crates/diff/benches/render.rs added +551 -0
1 +
//! Render benchmarks for `rustik-diff`.
2 +
//!
3 +
//! The benchmark decodes deterministic unified diffs once, then exercises
4 +
//! render, scroll, resize, focus, collapse, 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 +
    Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer, HighlightRequest, HighlightResult,
13 +
};
14 +
use rustik_tui::{Buffer, Color, Constraint, Label, Line, Rect, Scroll, Table, TableOptions};
15 +
16 +
/// Human-readable workload name printed by the benchmark report.
17 +
const WORKLOAD: &str = "rustik-diff-render";
18 +
/// Fixed terminal-sized render area.
19 +
const AREA: Rect = Rect::new(0, 0, 120, 40);
20 +
/// Narrow terminal area used by resize-heavy scenarios.
21 +
const NARROW_AREA: Rect = Rect::new(0, 0, 80, 24);
22 +
/// Wide terminal area used by resize-heavy scenarios.
23 +
const WIDE_AREA: Rect = Rect::new(0, 0, 180, 50);
24 +
/// Tiny terminal area used to stress minimum-width rendering.
25 +
const TINY_AREA: Rect = Rect::new(0, 0, 44, 12);
26 +
/// Default frame count.
27 +
const DEFAULT_FRAMES: usize = 80;
28 +
/// Default frame count for each workload in the full suite.
29 +
const DEFAULT_SUITE_FRAMES: usize = DEFAULT_FRAMES;
30 +
/// Default number of independent timed runs per workload.
31 +
const DEFAULT_RUNS: usize = 3;
32 +
/// Default number of file sections in the generated diff.
33 +
const DEFAULT_FILES: usize = 32;
34 +
/// Default number of hunk lines per generated file.
35 +
const DEFAULT_LINES: usize = 128;
36 +
/// One row sample stride for the checksum.
37 +
const SAMPLE_ROWS: usize = 5;
38 +
/// One column sample stride for the checksum.
39 +
const SAMPLE_COLS: usize = 7;
40 +
41 +
/// Runs the benchmark.
42 +
fn main() {
43 +
    let args = Args::parse();
44 +
    println!("{WORKLOAD} {}", args.workload.name());
45 +
    flush_stdout();
46 +
    let workloads = args.workload.expanded();
47 +
    let report_widths = ReportWidths::new(&workloads);
48 +
    let mut header = HeaderMode::Show;
49 +
    let reports = workloads
50 +
        .into_iter()
51 +
        .map(|workload| {
52 +
            let report = run_workload(workload, args);
53 +
            report_workload(&report, report_widths, header);
54 +
            header = HeaderMode::Hide;
55 +
            report
56 +
        })
57 +
        .collect::<Vec<_>>();
58 +
    let checksum = reports.iter().fold(0usize, |value, report| {
59 +
        value ^ report.checksum.rotate_left(report.workload as u32)
60 +
    });
61 +
62 +
    black_box(checksum);
63 +
    black_box(reports);
64 +
}
65 +
66 +
/// Benchmark command-line arguments.
67 +
#[derive(Clone, Copy, Debug)]
68 +
struct Args {
69 +
    /// Workload to run.
70 +
    workload: Workload,
71 +
    /// Number of frames to render.
72 +
    frames: FrameCount,
73 +
    /// Number of independent timed runs per workload.
74 +
    runs: usize,
75 +
    /// Number of synthetic file sections.
76 +
    files: usize,
77 +
    /// Number of synthetic hunk lines per file.
78 +
    lines: usize,
79 +
}
80 +
81 +
impl Args {
82 +
    /// Parses benchmark arguments from the process environment.
83 +
    fn parse() -> Self {
84 +
        Self::parse_from(std::env::args().skip(1))
85 +
    }
86 +
87 +
    /// Parses benchmark arguments from an iterator.
88 +
    fn parse_from(args: impl IntoIterator<Item = String>) -> Self {
89 +
        let mut parsed = Self {
90 +
            workload: Workload::All,
91 +
            frames: FrameCount::Default,
92 +
            runs: DEFAULT_RUNS,
93 +
            files: DEFAULT_FILES,
94 +
            lines: DEFAULT_LINES,
95 +
        };
96 +
        let mut args = args.into_iter();
97 +
98 +
        while let Some(arg) = args.next() {
99 +
            match arg.as_str() {
100 +
                "--workload" | "-w" => parsed.workload = next_workload(&mut args, parsed.workload),
101 +
                "--frames" => {
102 +
                    parsed.frames = FrameCount::Explicit(next_usize(&mut args, DEFAULT_FRAMES));
103 +
                }
104 +
                "--runs" => parsed.runs = next_usize(&mut args, parsed.runs).max(1),
105 +
                "--files" => parsed.files = next_usize(&mut args, parsed.files),
106 +
                "--lines" => parsed.lines = next_usize(&mut args, parsed.lines),
107 +
                "--help" | "-h" => {
108 +
                    println!(
109 +
                        "usage: cargo bench -p rustik-diff --bench render -- [--workload NAME] [--runs N] [--frames N] [--files N] [--lines N]"
110 +
                    );
111 +
                    std::process::exit(0);
112 +
                }
113 +
                value => {
114 +
                    if let Ok(value) = value.parse() {
115 +
                        parsed.frames = FrameCount::Explicit(value);
116 +
                    }
117 +
                }
118 +
            }
119 +
        }
120 +
121 +
        parsed
122 +
    }
123 +
}
124 +
125 +
/// Frame-count selection mode.
126 +
#[derive(Clone, Copy, Debug)]
127 +
enum FrameCount {
128 +
    /// Use workload-sensitive defaults.
129 +
    Default,
130 +
    /// Use the same explicit frame count for every selected workload.
131 +
    Explicit(usize),
132 +
}
133 +
134 +
impl FrameCount {
135 +
    /// Returns the concrete frame count for one workload.
136 +
    const fn for_workload(self, requested: Workload) -> usize {
137 +
        match (self, requested) {
138 +
            (Self::Default, Workload::All) => DEFAULT_SUITE_FRAMES,
139 +
            (Self::Default, _) => DEFAULT_FRAMES,
140 +
            (Self::Explicit(frames), _) => frames,
141 +
        }
142 +
    }
143 +
}
144 +
145 +
/// Named benchmark workload.
146 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
147 +
enum Workload {
148 +
    /// Original fixed-area, warm-cache, one-line scroll workload.
149 +
    WarmScroll,
150 +
    /// Mixed pager session with scrolling, navigation, resize, and collapse.
151 +
    Session,
152 +
    /// Width-changing render workload.
153 +
    Resize,
154 +
    /// Scrolling offsets concentrated around file boundaries.
155 +
    Sticky,
156 +
    /// Focus and collapse workload across many files.
157 +
    Collapse,
158 +
    /// Visible highlight request and row-refresh workload.
159 +
    Highlight,
160 +
    /// Large file-count workload with short hunks.
161 +
    ManyFiles,
162 +
    /// Single huge file workload.
163 +
    HugeFile,
164 +
    /// Long and Unicode-heavy source line workload.
165 +
    LongLines,
166 +
    /// Runs every named workload.
167 +
    All,
168 +
}
169 +
170 +
impl Workload {
171 +
    /// Returns concrete workloads represented by this value.
172 +
    fn expanded(self) -> Vec<Self> {
173 +
        match self {
174 +
            Self::All => vec![
175 +
                Self::WarmScroll,
176 +
                Self::Session,
177 +
                Self::Resize,
178 +
                Self::Sticky,
179 +
                Self::Collapse,
180 +
                Self::Highlight,
181 +
                Self::ManyFiles,
182 +
                Self::HugeFile,
183 +
                Self::LongLines,
184 +
            ],
185 +
            workload => vec![workload],
186 +
        }
187 +
    }
188 +
189 +
    /// Returns the workload display name.
190 +
    const fn name(self) -> &'static str {
191 +
        match self {
192 +
            Self::WarmScroll => "warm-scroll",
193 +
            Self::Session => "session",
194 +
            Self::Resize => "resize",
195 +
            Self::Sticky => "sticky",
196 +
            Self::Collapse => "collapse",
197 +
            Self::Highlight => "highlight",
198 +
            Self::ManyFiles => "many-files",
199 +
            Self::HugeFile => "huge-file",
200 +
            Self::LongLines => "long-lines",
201 +
            Self::All => "all",
202 +
        }
203 +
    }
204 +
205 +
    /// Returns the synthetic document shape for the workload.
206 +
    fn document_shape(self, args: Args) -> DiffShape {
207 +
        match self {
208 +
            Self::ManyFiles => DiffShape {
209 +
                files: args.files.max(1_024),
210 +
                lines: 12,
211 +
                hunk_lines: 6,
212 +
                profile: LineProfile::Tiny,
213 +
            },
214 +
            Self::HugeFile => DiffShape {
215 +
                files: 1,
216 +
                lines: args.lines.max(16_384),
217 +
                hunk_lines: 256,
218 +
                profile: LineProfile::Normal,
219 +
            },
220 +
            Self::LongLines => DiffShape {
221 +
                files: args.files,
222 +
                lines: args.lines,
223 +
                hunk_lines: 64,
224 +
                profile: LineProfile::LongUnicode,
225 +
            },
226 +
            Self::Sticky | Self::Collapse => DiffShape {
227 +
                files: args.files.max(256),
228 +
                lines: 32,
229 +
                hunk_lines: 16,
230 +
                profile: LineProfile::Normal,
231 +
            },
232 +
            Self::Session | Self::Resize | Self::Highlight | Self::WarmScroll | Self::All => {
233 +
                DiffShape {
234 +
                    files: args.files,
235 +
                    lines: args.lines,
236 +
                    hunk_lines: 64,
237 +
                    profile: LineProfile::Normal,
238 +
                }
239 +
            }
240 +
        }
241 +
    }
242 +
}
243 +
244 +
impl FromStr for Workload {
245 +
    type Err = ();
246 +
247 +
    fn from_str(value: &str) -> Result<Self, Self::Err> {
248 +
        match value {
249 +
            "warm-scroll" | "plain" | "scroll" => Ok(Self::WarmScroll),
250 +
            "session" => Ok(Self::Session),
251 +
            "resize" => Ok(Self::Resize),
252 +
            "sticky" | "sticky-boundaries" => Ok(Self::Sticky),
253 +
            "collapse" => Ok(Self::Collapse),
254 +
            "highlight" | "highlights" => Ok(Self::Highlight),
255 +
            "many-files" => Ok(Self::ManyFiles),
256 +
            "huge-file" => Ok(Self::HugeFile),
257 +
            "long-lines" => Ok(Self::LongLines),
258 +
            "all" => Ok(Self::All),
259 +
            _ => Err(()),
260 +
        }
261 +
    }
262 +
}
263 +
264 +
/// Shape of a generated diff document.
265 +
#[derive(Clone, Copy, Debug)]
266 +
struct DiffShape {
267 +
    /// Number of files to generate.
268 +
    files: usize,
269 +
    /// Number of source rows to generate per file.
270 +
    lines: usize,
271 +
    /// Maximum number of rows per hunk.
272 +
    hunk_lines: usize,
273 +
    /// Source-line content profile.
274 +
    profile: LineProfile,
275 +
}
276 +
277 +
/// Source-line text profile.
278 +
#[derive(Clone, Copy, Debug)]
279 +
enum LineProfile {
280 +
    /// Short Rust-like lines.
281 +
    Normal,
282 +
    /// Very small hunks for many-file workloads.
283 +
    Tiny,
284 +
    /// Wide rows with Unicode graphemes.
285 +
    LongUnicode,
286 +
}
287 +
288 +
/// Result from one workload run.
289 +
#[derive(Clone, Copy, Debug)]
290 +
struct BenchReport {
291 +
    /// Workload that produced the report.
292 +
    workload: Workload,
293 +
    /// Frame-rate statistics across independent runs.
294 +
    fps: RepeatStats,
295 +
    /// Combined deterministic render checksum across independent runs.
296 +
    checksum: usize,
297 +
}
298 +
299 +
/// Summary statistics for repeated benchmark runs.
300 +
#[derive(Clone, Copy, Debug)]
301 +
struct RepeatStats {
302 +
    /// Average frames per second.
303 +
    avg: f64,
304 +
    /// Frames-per-second standard deviation.
305 +
    stddev: f64,
306 +
}
307 +
308 +
/// Report column widths derived before workloads run.
309 +
#[derive(Clone, Copy, Debug)]
310 +
struct ReportWidths {
311 +
    /// Widest selected workload name.
312 +
    workload: usize,
313 +
    /// Width reserved for formatted frame rates.
314 +
    fps: usize,
315 +
}
316 +
317 +
const FPS_FORMAT: &str = "000000.0 fps";
318 +
319 +
/// Whether a streaming row should include the table header.
320 +
#[derive(Clone, Copy, Debug)]
321 +
enum HeaderMode {
322 +
    /// Print the header before the row.
323 +
    Show,
324 +
    /// Print only the data row.
325 +
    Hide,
326 +
}
327 +
328 +
/// Parses the next argument as a `usize`.
329 +
fn next_usize(args: &mut impl Iterator<Item = String>, fallback: usize) -> usize {
330 +
    args.next()
331 +
        .and_then(|value| value.parse().ok())
332 +
        .unwrap_or(fallback)
333 +
}
334 +
335 +
/// Parses the next argument as a workload.
336 +
fn next_workload(args: &mut impl Iterator<Item = String>, fallback: Workload) -> Workload {
337 +
    args.next()
338 +
        .and_then(|value| value.parse().ok())
339 +
        .unwrap_or(fallback)
340 +
}
341 +
342 +
/// Runs one named benchmark workload.
343 +
fn run_workload(workload: Workload, args: Args) -> BenchReport {
344 +
    let frames = args.frames.for_workload(args.workload);
345 +
    let shape = workload.document_shape(args);
346 +
    let input = synthetic_diff(shape);
347 +
    let document = match DiffDocument::decode_str(&input) {
348 +
        Ok(document) => document,
349 +
        Err(error) => {
350 +
            eprintln!("failed to decode generated benchmark diff: {error}");
351 +
            std::process::exit(1);
352 +
        }
353 +
    };
354 +
    let rows = DiffViewer::new(document.clone(), DiffOptions::default()).content_rows(AREA.cols);
355 +
    let mut fps = Vec::with_capacity(args.runs);
356 +
    let mut checksum = rows;
357 +
358 +
    for run in 0..args.runs {
359 +
        let (run_elapsed, run_checksum) = run_once(workload, document.clone(), frames);
360 +
        fps.push(frames as f64 / run_elapsed.as_secs_f64());
361 +
        checksum ^= run_checksum.rotate_left((run % usize::BITS as usize) as u32);
362 +
    }
363 +
364 +
    BenchReport {
365 +
        workload,
366 +
        fps: RepeatStats::from_values(&fps),
367 +
        checksum,
368 +
    }
369 +
}
370 +
371 +
/// Runs one independent timed pass for a workload.
372 +
fn run_once(workload: Workload, document: DiffDocument, frames: usize) -> (Duration, usize) {
373 +
    match workload {
374 +
        Workload::WarmScroll => run_warm_scroll(document, frames),
375 +
        Workload::Session => run_session(document, frames),
376 +
        Workload::Resize => run_resize(document, frames),
377 +
        Workload::Sticky => run_sticky(document, frames),
378 +
        Workload::Collapse => run_collapse(document, frames),
379 +
        Workload::Highlight => run_highlight(document, frames),
380 +
        Workload::ManyFiles => run_session(document, frames),
381 +
        Workload::HugeFile => run_sticky(document, frames),
382 +
        Workload::LongLines => run_resize(document, frames),
383 +
        Workload::All => unreachable!("run_once: all is expanded before dispatch"),
384 +
    }
385 +
}
386 +
387 +
/// Renders a fixed-area warm-cache scrolling workload.
388 +
fn run_warm_scroll(document: DiffDocument, frames: usize) -> (Duration, usize) {
389 +
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
390 +
    let mut buffer = Buffer::empty(AREA);
391 +
    let start = Instant::now();
392 +
    let mut checksum = 0usize;
393 +
394 +
    for frame in 0..frames {
395 +
        buffer.clear();
396 +
        viewer.render(AREA, &mut buffer);
397 +
        checksum ^= sample_buffer(&buffer, frame);
398 +
        viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA);
399 +
        buffer.reset_dirty();
400 +
    }
401 +
402 +
    (start.elapsed(), checksum)
403 +
}
404 +
405 +
/// Renders a mixed pager session.
406 +
fn run_session(document: DiffDocument, frames: usize) -> (Duration, usize) {
407 +
    let areas = [AREA, AREA, WIDE_AREA, AREA, NARROW_AREA, AREA];
408 +
    run_scripted(document, frames, |viewer, frame| {
409 +
        let area = areas[frame % areas.len()];
410 +
        match frame % 24 {
411 +
            0 => apply_resize(viewer, area),
412 +
            1..=6 => {
413 +
                viewer.apply(DiffAction::Scroll(Scroll::Lines(3)), area);
414 +
            }
415 +
            7 => {
416 +
                viewer.apply(
417 +
                    DiffAction::Scroll(Scroll::Lines((area.rows / 2) as isize)),
418 +
                    area,
419 +
                );
420 +
            }
421 +
            8 => {
422 +
                viewer.apply(DiffAction::NextHunk, area);
423 +
            }
424 +
            9 => {
425 +
                viewer.apply(DiffAction::FocusNext, area);
426 +
            }
427 +
            10 => {
428 +
                viewer.apply(DiffAction::ToggleFocusedFile, area);
429 +
            }
430 +
            11 => {
431 +
                viewer.apply(DiffAction::ToggleFocusedFile, area);
432 +
            }
433 +
            12 => {
434 +
                viewer.apply(DiffAction::PreviousHunk, area);
435 +
            }
436 +
            _ => {
437 +
                viewer.apply(DiffAction::Scroll(Scroll::Lines(-1)), area);
438 +
            }
439 +
        }
440 +
        area
441 +
    })
442 +
}
443 +
444 +
/// Renders while invalidating width-dependent caches with resize events.
445 +
fn run_resize(document: DiffDocument, frames: usize) -> (Duration, usize) {
446 +
    let areas = [AREA, WIDE_AREA, NARROW_AREA, TINY_AREA, AREA];
447 +
    run_scripted(document, frames, |viewer, frame| {
448 +
        let area = areas[frame % areas.len()];
449 +
        apply_resize(viewer, area);
450 +
        viewer.apply(
451 +
            DiffAction::Scroll(Scroll::Lines((frame % 7) as isize - 3)),
452 +
            area,
453 +
        );
454 +
        area
455 +
    })
456 +
}
457 +
458 +
/// Renders offsets concentrated around sticky file-header transitions.
459 +
fn run_sticky(document: DiffDocument, frames: usize) -> (Duration, usize) {
460 +
    run_scripted(document, frames, |viewer, frame| {
461 +
        if frame % 16 == 0 {
462 +
            viewer.apply(DiffAction::FocusNext, AREA);
463 +
        } else if frame % 16 < 8 {
464 +
            viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), AREA);
465 +
        } else {
466 +
            viewer.apply(DiffAction::Scroll(Scroll::Lines(-1)), AREA);
467 +
        }
468 +
        AREA
469 +
    })
470 +
}
471 +
472 +
/// Renders while repeatedly focusing and collapsing file cards.
473 +
fn run_collapse(document: DiffDocument, frames: usize) -> (Duration, usize) {
474 +
    run_scripted(document, frames, |viewer, frame| {
475 +
        match frame % 6 {
476 +
            0 => {
477 +
                viewer.apply(DiffAction::FocusNext, AREA);
478 +
            }
479 +
            1 => {
480 +
                viewer.apply(DiffAction::CollapseFocusedFile, AREA);
481 +
            }
482 +
            2 => {
483 +
                viewer.apply(DiffAction::ToggleFocusedFile, AREA);
484 +
            }
485 +
            3 => {
486 +
                viewer.apply(DiffAction::NextHunk, AREA);
487 +
            }
488 +
            _ => {
489 +
                viewer.apply(DiffAction::Scroll(Scroll::Lines(3)), AREA);
490 +
            }
491 +
        }
492 +
        AREA
493 +
    })
494 +
}
495 +
496 +
/// Renders while applying synthetic highlight results for visible rows.
497 +
fn run_highlight(document: DiffDocument, frames: usize) -> (Duration, usize) {
498 +
    run_scripted(document, frames, |viewer, frame| {
499 +
        let requests = viewer.visible_highlight_requests(AREA);
500 +
        viewer.apply_highlights(requests.into_iter().take(AREA.rows).map(highlight_result));
501 +
        viewer.apply(
502 +
            DiffAction::Scroll(Scroll::Lines((frame % 5 + 1) as isize)),
503 +
            AREA,
504 +
        );
505 +
        AREA
506 +
    })
507 +
}
508 +
509 +
/// Renders frames using a caller-provided action script.
510 +
fn run_scripted(
511 +
    document: DiffDocument,
512 +
    frames: usize,
513 +
    mut script: impl FnMut(&mut DiffViewer, usize) -> Rect,
514 +
) -> (Duration, usize) {
515 +
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
516 +
    let mut buffer = Buffer::empty(AREA);
517 +
    let start = Instant::now();
518 +
    let mut checksum = 0usize;
519 +
520 +
    for frame in 0..frames {
521 +
        let area = script(&mut viewer, frame);
522 +
        buffer.resize(area);
523 +
        buffer.clear();
524 +
        viewer.render(area, &mut buffer);
525 +
        checksum ^= sample_buffer(&buffer, frame);
526 +
        buffer.reset_dirty();
527 +
    }
528 +
529 +
    (start.elapsed(), checksum)
530 +
}
531 +
532 +
/// Applies resize handling for an area.
533 +
fn apply_resize(viewer: &mut DiffViewer, area: Rect) {
534 +
    viewer.apply(DiffAction::Resize, area);
535 +
}
536 +
537 +
/// Converts a highlight request into a deterministic synthetic result.
538 +
fn highlight_result(request: HighlightRequest) -> HighlightResult {
539 +
    HighlightResult {
540 +
        key: request.key,
541 +
        line: Line::new(Label::from(request.text).fg(Color::Yellow)),
542 +
    }
543 +
}
544 +
545 +
/// Creates a deterministic Git-style unified diff.
546 +
fn synthetic_diff(shape: DiffShape) -> String {
547 +
    let mut diff = String::new();
548 +
549 +
    for file in 0..shape.files {
550 +
        diff.push_str(&format!(
551 +
            "
src/file_{file:04}.rs\n" +0 -0