Benchmarking & Profiling
local graph
Chapter 10 — Benchmarking & Profiling
Section titled “Chapter 10 — Benchmarking & Profiling”Chapter 10 – Benchmarking & Profiling
Section titled “Chapter 10 – Benchmarking & Profiling”Performance matters—whether you’re processing a million records or animating at 60 fps, understanding where time is spent helps you squeeze out every millisecond.
10.1: Using Criterion in Wasm
Section titled “10.1: Using Criterion in Wasm”Benchmarking your Rust code in Wasm demands both precision and realism. Criterion.rs is the gold-standard Rust benchmarking harness—it applies statistical analysis to measure performance variations. By running Criterion benchmarks against your Wasm module (in Node.js or headless browsers), you’ll get accurate insights into where your code spends time, and you’ll avoid flukes from JIT warm-up or noise. Let’s walk through setting up Criterion for Wasm.
A. Why Criterion for Wasm?
Section titled “A. Why Criterion for Wasm?”- Statistical Rigor: It performs many iterations, discards outliers, and reports means with confidence intervals.
- Comparisons: Easily compare two implementations (e.g., before and after an optimization).
- Extensible: Works in native Rust, and with a small adjustment, in Wasm via
wasm-bindgen-testand Node.
Personal Insight: In a parse-heavy module, Criterion exposed that a naïve UTF-8 decoder was 30 % slower than Rust’s built-in—saving me hours of guesswork.
B. Setting Up Your Benchmark Crate
Section titled “B. Setting Up Your Benchmark Crate”- Add dependencies to your
Cargo.toml:
[dev-dependencies] criterion = “0.4” wasm-bindgen-test = “0.3”
[lib] crate-type = [“cdylib”, “rlib”]
[dependencies] wasm-bindgen = “0.2”
- criterion for benchmarking
- wasm-bindgen-test to run tests and benchmarks in Wasm contexts
-
Enable the Wasm test harness at the top of your bench file:
-
// benches/wasm_bench.rs
-
use wasm_bindgen_test::*;
-
wasm_bindgen_test_configure!(run_in_node); // or run_in_browser
C. Writing a Criterion Benchmark
// benches/wasm_bench.rs use criterion::{criterion_group, criterion_main, Criterion}; use wasm_bindgen_test::*; use my_crate::compute_intensive; // your Wasm-exported function
wasm_bindgen_test_configure!(run_in_node);
fn bench_compute(c: &mut Criterion) {
// Prepare input once (e.g., a large buffer)
let data: Vec
c.bench_function("compute_intensive", |b| { b.iter(|| { // Each iteration calls into Wasm compute_intensive(&data); })});}
criterion_group!( name = benches; config = Criterion::default().sample_size(50); targets = bench_compute );
criterion_main!(benches);
sample_size(50): Controls how many times each measurement repeats—tweak for stability.bench_function: Names the test in the report.b.iter(|| ...): The closure under test.
D. Running in Node.js
# Build your crate in release modecargo build --release
# Run benchmarks in Node via wasm-packwasm-pack test --node -- --nocapture --benchCriterion will output something like:
compute_intensivetime: [2.345 ms 2.367 ms 2.392 ms]change: [+0.5% +1.2% +2.0%] (p = 0.01 < 0.05)Performance has regressed.--nocapture: Shows printouts if you println! inside the bench.--bench: Tells wasm-bindgen-test to run benches, not just unit tests.
E. Running in a Headless Browser
For browser-specific optimizations (e.g., JIT behavior):
wasm-pack test --chrome -- --nocapture --bench- Opens a headless Chrome.
- Runs the Criterion harness in the browser’s JS environment.
- Prints results back to your terminal.
Expert Tip: Ensure Chrome’s version is pinned in CI to prevent benchmark drift across updates.
F. Interpreting Results & Comparing Implementations
Section titled “F. Interpreting Results & Comparing Implementations”Criterion writes output to target/criterion. You can open index.html in that folder to see interactive charts:
- Latency distribution: Violin plots show variability.
- Regression comparisons: If you commit a change and rerun, it highlights performance improvements or regressions.
Performance difference between baseline and current:
compute_intensive 2.35 ms (baseline) → 2.10 ms (optimized) Change speed: -10.6% (p < 0.05)
G. Case Study: Optimizing a Parser
Section titled “G. Case Study: Optimizing a Parser”Scenario: A JSON parser running in Wasm was taking ~5 ms per document. After identifying a hotspot via Criterion, I replaced a generic Vec::insert usage with a Vec::push + reverse trick, cutting runtime to ~3 ms—a 40 % gain verified by consistent Criterion reports across 100+ runs.
Key Takeaways
Section titled “Key Takeaways”- Criterion.rs gives you statistically valid benchmarks, even in Wasm.
- Separate your benches into benches/ and use wasm-bindgen-test to run in Node or headless browsers.
- Fine-tune sample sizes for stability, and pin your runtime environments in CI.
- Visualize reports with the HTML output for team discussions and regression tracking.
10.2: Startup Time vs. Execution Time
Section titled “10.2: Startup Time vs. Execution Time”When you load a Rust–Wasm module in the browser, two distinct costs emerge:
- Startup Time: The cost of fetching, instantiating, and initializing the Wasm module (including any JS “glue” setup).
- Execution Time: The cost of calling your exported functions once the module is ready.
Measuring them separately helps you optimize the parts that matter most for your users—whether that’s first render speed or per-interaction snappiness.
flowchart LR subgraph Startup Measurement A[Begin timer] —> B[fetch + instantiate Wasm] B —> C[call init()] —> D[End timer: StartupTime] end subgraph Execution Measurement E[Begin timer] —> F[call exported_fn(…)] —> G[End timer: ExecutionTime] end D & G —> H[Log / Analyze Separately]
---
## A. Measuring Startup Time
Startup includes:
- **Network**: Downloading the `.wasm` and JS files- **Compilation/Instantiation**: Browser compiles Wasm to native- **Glue Initialization**: Any work in `#[wasm_bindgen(start)]`
### 1. JavaScript Example
```html<script type="module"> import init from './pkg/my_crate.js';
async function measureStartup() { const t0 = performance.now();await init(); // Downloads + compiles + runs start hook
const t1 = performance.now();
console.log(Wasm startup: ${ (t1 - t0).toFixed(2) } ms);
measureStartup().catch(console.error);
2. Fetch + InstantiateStreaming
Section titled “2. Fetch + InstantiateStreaming”If you bypass wasm-pack glue, you can separate network vs. compile:
async function measureRawStartup() {
const t0 = performance.now();
const resp = await fetch(‘my_crate_bg.wasm’);
const t1 = performance.now();
const bytes = await resp.arrayBuffer();
const t2 = performance.now();
const mod = await WebAssembly.instantiate(bytes);
const t3 = performance.now();
console.log(Fetch: ${ (t1 - t0).toFixed(2) } ms);
console.log(ArrayBuffer: ${ (t2 - t1).toFixed(2) } ms);
console.log(Instantiate: ${ (t3 - t2).toFixed(2) } ms);
}
measureRawStartup();
Insight: You may find that network time dwarfs compile time on slow connections, shifting your optimization focus to compression (Brotli/GZIP).
B. Measuring Execution Time
Section titled “B. Measuring Execution Time”Once the module is warm, each exported function call has its own cost. Measure it in isolation:
- Warm-up mitigates JIT or caching effects.- Batching reduces measurement noise.
---
## C. Visualizing Results
Use simple tables or charts to compare:
<table> <thead> <tr> <th>Metric</th> <th>Time (ms)</th> </tr> </thead> <tbody> <tr> <td>Startup</td> <td>120.45</td> </tr> <tr> <td>Execution (avg)</td> <td>2.37</td> </tr> </tbody></table>
Or plot in JS via `console.table`. For more, export to CSV for external graphing.
---
## D. Case Study: Lazy Initialization
**Scenario:** A data-visualization widget took ~200 ms to start—too long for first interaction. By deferring non-critical setup (loading background data, registering event listeners) until after the first frame, we cut perceived
<!-- page: 126 -->
startup to under 50 ms.
Implementation: Moved heavy #[wasm_bindgen(start)] tasks into an explicit initAsync() that the app calls after rendering a loading spinner. Execution timing remained the same, but users saw content sooner.
---
Key Takeaways
- Separate startup from execution measurements to identify which to optimize.- Use performance.now() for sub-millisecond precision in both cases.- Batch calls and warm up to reduce noise in execution timing.- Defer non-critical work to shrink perceived startup latency, even if total work remains constant.
---
10.3: Flamegraphs and Waterfall Charts
Raw timing numbers are great, but visualizing where time goes—whether in deep call stacks or across network requests—gives you an immediate, intuitive map of bottlenecks. Flamegraphs expose hot code paths; waterfall charts reveal network and scheduling delays. Let’s walk through both, with practical steps, diagrams, and tips.
---
A. Generating a Flamegraph in Chrome DevTools
A flamegraph shows function-call hierarchies along the Y-axis, with horizontal width proportional to time spent.
flowchart LRA[Open DevTools → Performance] --> B[Enable Wasm & JS Sampling]B --> C[Click Record]C --> D[Run your scenario]D --> E[Stop Recording]E --> F[View Flame Chart in DevTools]
<!-- page: 127 -->
1. Open Performance Panel - In Chrome: F12 → Performance.
2. Enable WebAssembly Profiling - Click the gear ⚙️ and check “WebAssembly” under “CPU Profiler”.
3. Record - Click the red ● Record button. - Perform the actions you want to profile (e.g., call your Wasm function or run an animation). - Click ■ Stop when done.
4. View the Flame Chart - Switch to “Flame Chart” view. - Hover or click a bar to see the call stack: Rust functions appear by their original .rs names if you generated source maps.
5. Identify Hotspots - Look for wide bars near the top of the chart—these are the routines consuming the most time.
Personal Insight: I once discovered that a seemingly innocuous helper function was chewing up 20 ms per frame—visible instantly in the flamegraph—and eliminated it in favor of a one-line inline, instantly boosting my 60 fps animation.
---
B. Exporting and Sharing with Speedscope
For team collaboration or deeper analysis:
1. Export Profile - In Performance panel, click the “Export” icon → “Speedscope (JSON)”. - Save the .json file.
2. Load in Speedscope - Go to <https://www.speedscope.app/>. - Open your exported file.
3. Interactively Explore - Switch between “Left Heavy” (bottom-up) and “Sandwich” (flame) views. - Search for specific function names (e.g., process_buffer).
<!-- page: 128 -->
Case Study: Sharing a Speedscope link with my team helped us pinpoint that our CSV parser was spending 30 % of its time in string reallocation—a finding that led to a Monday-morning refactor that cut end-to-end parsing time by 40 %.
---
C. Waterfall Charts for Network & Instantiation
While flamegraphs focus on CPU, waterfall charts show when resources load and how async operations overlap.
flowchart LRA[Open DevTools → Network] --> B[Ensure “Disable cache” is off]B --> C[Reload page]C --> D[Observe waterfall bars for .wasm, .js, XHR, etc.]D --> E[Analyze timings: DNS, TCP, TLS, Download, TTFB]
1. Open the Network Panel - F12 → Network.2. Disable Cache (optional) - Check “Disable cache” to simulate a cold load.3. Reload the Page - Press Ctrl + R (Win) or ⌘ + R (Mac).4. Read the Waterfall - Each row is a resource (e.g., my_crate_bg.wasm, JS glue, CSS). - The colored segments represent DNS lookup, TCP handshake, TLS, download, and “processing” (including Wasm compilation).5. Spot Bottlenecks - A long “Download” on the .wasm suggests compression is needed. - A long “Processing” phase indicates Wasm compilation time—consider streaming compilation or lazy instantiation.
Expert Tip: On mobile throttling (e.g., 3G simulation), you might see network dominate—opt for smaller .wasm builds or HTTP/2 push to hide latency.
---
<!-- page: 129 -->
# D. Combining Flamegraphs & Waterfalls
By correlating the two:
- **Waterfall** tells you when the module becomes available and how long compile takes.- **Flamegraph** shows where time goes after instantiation, during runtime.
Use both to answer:
- “Is my init time too long?” Waterfall- “Which function is slow?” Flamegraph
---
## Key Takeaways
- **Flamegraphs** map CPU time across your call stacks—use DevTools or Speedscope to explore.- **Waterfall charts** reveal resource load times and Wasm compile delays—use the Network panel.- **Source maps** are your friend: generate them to see Rust function names instead of raw bytecode offsets.- **Simulate slow networks** to capture real-world startup scenarios and optimize accordingly.
With flamegraphs and waterfalls in your arsenal, you’ll confidently identify and eliminate performance hurdle.
---