Skip to content

Commit

Permalink
test(block): add benchmarks (#368)
Browse files Browse the repository at this point in the history
Added benchmarks to the block widget to uncover eventual performance issues
  • Loading branch information
Valentin271 committed Aug 5, 2023
1 parent aad164a commit e18393d
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ rand = "0.8"
name = "paragraph"
harness = false

[[bench]]
name = "block"
harness = false


[[example]]
name = "barchart"
required-features = ["crossterm"]
Expand Down
58 changes: 58 additions & 0 deletions benches/block.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use criterion::{criterion_group, criterion_main, Bencher, BenchmarkId, Criterion};
use ratatui::{
buffer::Buffer,
layout::Rect,
prelude::Alignment,
widgets::{
block::{Position, Title},
Block, Borders, Padding, Widget,
},
};

/// Benchmark for rendering a block.
pub fn block(c: &mut Criterion) {
let mut group = c.benchmark_group("block");

for buffer_size in &[
Rect::new(0, 0, 100, 50), // vertically split screen
Rect::new(0, 0, 200, 50), // 1080p fullscreen with medium font
Rect::new(0, 0, 256, 256), // Max sized area
] {
let buffer_area = buffer_size.area();

// Render an empty block
group.bench_with_input(
BenchmarkId::new("render_empty", buffer_area),
&Block::new(),
|b, block| render(b, block, buffer_size),
);

// Render with all features
group.bench_with_input(
BenchmarkId::new("render_all_feature", buffer_area),
&Block::new()
.borders(Borders::ALL)
.title("test title")
.title(
Title::from("bottom left title")
.alignment(Alignment::Right)
.position(Position::Bottom),
)
.padding(Padding::new(5, 5, 2, 2)),
|b, block| render(b, block, buffer_size),
);
}

group.finish();
}

/// render the block into a buffer of the given `size`
fn render(bencher: &mut Bencher, block: &Block, size: &Rect) {
let mut buffer = Buffer::empty(*size);
bencher.iter(|| {
block.clone().render(buffer.area, &mut buffer);
})
}

criterion_group!(benches, block);
criterion_main!(benches);

0 comments on commit e18393d

Please sign in to comment.