Skip to main content

buffer_stream_bench/
buffer_stream_bench.rs

1//! Compare caller-buffer streaming and one-shot codec throughput.
2use meshoptimizer_rs::{codec::*, Limits, Workspace};
3use std::{
4    hint::black_box,
5    time::{Duration, Instant},
6};
7// Timed by default. `BENCH_ONLY=<substring of a case name>` runs just the
8// matching cases and `BENCH_RUNS=<n>` runs exactly n iterations of each, so
9// `perf stat -e instructions:u` (minus a `BENCH_ONLY=none` run for the setup)
10// gives instructions per decoded byte independent of machine load.
11fn measure(name: &str, mut f: impl FnMut(), bytes: usize) -> f64 {
12    if std::env::var("BENCH_ONLY").is_ok_and(|only| !name.contains(&only)) {
13        return 1.0;
14    }
15    let start = Instant::now();
16    let mut runs = 0u32;
17    if let Some(fixed) = std::env::var("BENCH_RUNS")
18        .ok()
19        .and_then(|n| n.parse::<u32>().ok())
20    {
21        for _ in 0..fixed {
22            f();
23        }
24        return fixed as f64;
25    }
26    while start.elapsed() < Duration::from_millis(500) {
27        f();
28        runs += 1;
29    }
30    bytes as f64 * f64::from(runs) / start.elapsed().as_secs_f64() / 1e6
31}
32fn main() {
33    let n = 65536;
34    let stride = 32;
35    // Smooth per-vertex attributes with small deterministic noise.
36    let mut rng = 1u32;
37    let vertices: Vec<u8> = (0..n)
38        .flat_map(|v| {
39            (0..stride / 4)
40                .flat_map(|k| {
41                    rng ^= rng << 13;
42                    rng ^= rng >> 17;
43                    rng ^= rng << 5;
44                    let value = (v * (k + 1) * 3) as u32 + (rng & 7);
45                    value.to_le_bytes()
46                })
47                .collect::<Vec<_>>()
48        })
49        .collect();
50    // A 256 x 256 vertex grid of quads, two triangles each, in row order.
51    let indices: Vec<u32> = (0..255u32)
52        .flat_map(|y| (0..255u32).map(move |x| (x, y)))
53        .flat_map(|(x, y)| {
54            let a = y * 256 + x;
55            [a, a + 1, a + 256, a + 1, a + 257, a + 256]
56        })
57        .collect();
58    for version in 0..=1 {
59        let v = encode_vertex_buffer(
60            &vertices,
61            n,
62            stride,
63            VertexEncoding::new(version, 2).unwrap(),
64            &mut Workspace::default(),
65        )
66        .unwrap();
67        let t = encode_index_buffer(
68            &indices,
69            IndexEncoding::new(version).unwrap(),
70            &mut Workspace::default(),
71        )
72        .unwrap();
73        let mut vo = vec![0; vertices.len()];
74        let mut to = vec![0; indices.len() * 4];
75        let vb = vo.len();
76        let tb = to.len();
77        let vm = measure(
78            &format!("v{version}:vertex:oneshot"),
79            || {
80                decode_vertex_buffer_into(
81                    black_box(&mut vo),
82                    n,
83                    stride,
84                    &v,
85                    &mut Workspace::default(),
86                )
87                .unwrap()
88            },
89            vb,
90        );
91        let tm = measure(
92            &format!("v{version}:tri:oneshot"),
93            || {
94                decode_index_buffer_into(
95                    black_box(&mut to),
96                    indices.len(),
97                    4,
98                    &t,
99                    &mut Workspace::default(),
100                )
101                .unwrap()
102            },
103            tb,
104        );
105        println!("v{version} one-shot vertex={vm:.2} triangle={tm:.2} MB/s decoded");
106        for chunk in [4096, 65536] {
107            let tail = (stride + if version == 0 { 0 } else { stride / 4 }).max(if version == 0 {
108                32
109            } else {
110                24
111            });
112            let end = v.len() - tail;
113            let size = vo.len();
114            let rate = measure(
115                &format!("v{version}:vertex:{chunk}"),
116                || {
117                    let mut d = VertexBufferDecoder::new(
118                        n,
119                        stride,
120                        v[0],
121                        &v[end..],
122                        end - 1,
123                        Limits::default(),
124                    )
125                    .unwrap();
126                    let (mut at, mut out) = (1, 0);
127                    loop {
128                        let p = d
129                            .push(&v[at..(at + chunk).min(end)], &mut vo[out..])
130                            .unwrap();
131                        at += p.consumed;
132                        out += p.written;
133                        if p.status == Status::Done {
134                            break;
135                        }
136                    }
137                    d.finish().unwrap();
138                    black_box(&vo);
139                },
140                size,
141            );
142            let mut output = vec![0u32; indices.len()];
143            let rate_t = measure(
144                &format!("v{version}:tri:{chunk}"),
145                || {
146                    let start = 1 + indices.len() / 3;
147                    let end = t.len() - 16;
148                    let mut d = IndexBufferDecoder::new(
149                        indices.len(),
150                        &t[..start],
151                        &t[end..],
152                        end - start,
153                        Limits::default(),
154                    )
155                    .unwrap();
156                    let (mut at, mut out) = (start, 0);
157                    loop {
158                        let p = d
159                            .push(&t[at..(at + chunk).min(end)], &mut output[out..])
160                            .unwrap();
161                        at += p.consumed;
162                        out += p.written;
163                        if p.status == Status::Done {
164                            break;
165                        }
166                    }
167                    d.finish().unwrap();
168                    black_box(&output);
169                },
170                to.len(),
171            );
172            println!(
173                "v{version} chunk={chunk} vertex={rate:.2} ({:.3}x) triangle={rate_t:.2} ({:.3}x)",
174                rate / vm,
175                rate_t / tm
176            );
177        }
178    }
179}