Add more robust benchmarks (#165)
1//! This file includes benchmarks for very large, pseudo-randomly generated trees
2use criterion::{criterion_group, criterion_main, Criterion};
3use rand::prelude::*;
4use rand_chacha::ChaCha8Rng;
5use taffy::prelude::*;
6use taffy::randomizable::Randomizeable;
7use taffy::style::FlexboxLayout;
8
9/// The number of nodes to include in the trees
10const NODE_COUNT: u32 = 100_000;
11
12/// Build a random leaf node
13fn build_random_leaf(taffy: &mut Taffy, rng: &mut ChaCha8Rng) -> Node {
14 taffy.new_with_children(FlexboxLayout::random(rng), &[]).unwrap()
15}
16
17/// A tree with many children that have shallow depth
18fn build_flat_hierarchy(taffy: &mut Taffy) -> Node {
19 let mut rng = ChaCha8Rng::seed_from_u64(12345);
20 let mut children = Vec::new();
21 let mut node_count = 0;
22
23 while node_count < NODE_COUNT {
24 let sub_children_count = rng.gen_range(1..=4);
25 let sub_children: Vec<Node> = (0..sub_children_count).map(|_| build_random_leaf(taffy, &mut rng)).collect();
26 let node = taffy.new_with_children(FlexboxLayout::random(&mut rng), &sub_children).unwrap();
27
28 children.push(node);
29 node_count += 1 + sub_children_count;
30 }
31
32 taffy.new_with_children(FlexboxLayout { ..Default::default() }, children.as_slice()).unwrap()
33}
34
35/// A helper function to recursively construct a deep tree
36fn build_deep_tree(taffy: &mut Taffy, rng: &mut ChaCha8Rng, max_nodes: u32) -> Vec<Node> {
37 let branching_factor = 7;
38
39 if max_nodes <= branching_factor {
40 // Build leaf nodes
41 return (0..max_nodes).map(|_| build_random_leaf(taffy, rng)).collect();
42 }
43
44 // Add another layer to the tree
45 // Each child gets an equal amount of the remaining nodes
46 (0..branching_factor)
47 .map(|_| {
48 let sub_children = build_deep_tree(taffy, rng, (max_nodes - branching_factor) / branching_factor);
49 taffy.new_with_children(FlexboxLayout::random(rng), &sub_children).unwrap()
50 })
51 .collect()
52}
53
54/// A tree with a higher depth for a more realistic scenario
55fn build_deep_hierarchy(taffy: &mut Taffy) -> Node {
56 let mut rng = ChaCha8Rng::seed_from_u64(12345);
57
58 let tree = build_deep_tree(taffy, &mut rng, NODE_COUNT);
59
60 taffy.new_with_children(FlexboxLayout { ..Default::default() }, &tree).unwrap()
61}
62
63fn taffy_benchmarks(c: &mut Criterion) {
64 // Decrease sample size, because the tasks take longer
65 let mut group = c.benchmark_group("big tree (100_000 nodes)");
66 group.sample_size(10);
67
68 group.bench_function("flat hierarchy", |b| {
69 let mut taffy = Taffy::new();
70 let root = build_flat_hierarchy(&mut taffy);
71
72 b.iter(|| taffy.compute_layout(root, Size::NONE).unwrap())
73 });
74
75 group.bench_function("deep hierarchy", |b| {
76 let mut taffy = Taffy::new();
77 let root = build_deep_hierarchy(&mut taffy);
78
79 b.iter(|| taffy.compute_layout(root, Size::NONE).unwrap())
80 });
81}
82
83criterion_group!(benches, taffy_benchmarks);
84criterion_main!(benches);