Unsafe Engineering · 18 min · free lesson

Benchmark & Profile

Find the real bottleneck before optimizing.

Core idea

A benchmark measures a stable workload; a profiler explains where its time or allocations go.

Diagram for Benchmark & Profile: a Rust code example flows to the lesson rule and the key observation.
Instant times one run of workload, and black_box discourages the compiler from removing it.

Understand it

A benchmark measures a stable workload; a profiler explains where its time or allocations go. Change one variable, protect against optimized-away work, and compare distributions rather than one lucky run.

A benchmark asks how a specific workload behaves under controlled conditions. A profiler asks where time, allocations, or waits occur during that workload. Start with a question that matters to a user, such as median parse latency for a typical file or worst-case response time for a large project. Use a release build, warm up when appropriate, and keep input, hardware, and environment stable between comparisons. One Instant measurement is useful for a quick observation but too noisy to settle a small optimization.

A compiler may remove work whose result is unused, so a benchmark must keep the result observable; black_box can help prevent an obvious optimization in a microbenchmark but does not make the benchmark realistic by itself. Record a distribution over repeated runs and look for variance from caching, scheduling, and I/O. Profile the slow case before changing code. If allocations dominate, reserve capacity or borrow data; if the algorithm scales poorly, a container or complexity change may matter more. Change one variable, rerun the same workload, and keep a correctness test. Report both the improvement and its cost in memory, code complexity, or startup time.

For a before-and-after report, include the input shape, sample count, median and slower-tail observations, build mode, and what you held constant. If the result is within the noise, say so. A useful profile names the expensive path and gives enough context to reproduce it; a colorful flame graph without a workload description is not an engineering conclusion.

Read the code

let start = std::time::Instant::now();
let answer = workload();
std::hint::black_box(answer);
println!("{:?}", start.elapsed());

Instant times one run of workload, and black_box discourages the compiler from removing it.

Practice starter

use std::hint::black_box;
use std::time::Instant;

fn main() {
    let input: Vec<u64> = (0..1_000_000).collect();
    let mut samples = Vec::new();
    for _ in 0..5 {
        let start = Instant::now();
        let total: u64 = black_box(&input).iter().sum();
        black_box(total);
        samples.push(start.elapsed());
    }
    samples.sort();
    println!("median {:?}", samples[2]);
}

Practise this code in Playground ↗

Try it

Run this in a debug and a release build and compare the medians. Then change iter().sum() to a version you think is faster, and report both numbers.

What success looks like: You can report sample count, median, and build mode, and say whether the change beats the noise.

Check your understanding

What should happen before optimization?

Reveal the answer
  1. Measure a workload
  2. Rewrite the hot loop from intuition
  3. Raise opt-level blindly

A measured workload tells you what is slow and gives a number to compare after a change. A rewrite from intuition or a higher opt-level without one is a guess.

Go deeper

Common misconception: “A single fast timing is enough to tell which version is better.”

A benchmark measures a stable workload; a profiler explains where its time or allocations go. One timing is too noisy, so compare repeated runs under the same conditions.

  1. Start the clock: Instant::now() is taken before the call, so the reading covers workload() and everything up to elapsed().
  2. Keep the result: black_box(answer) discourages the compiler from treating answer as unused, so the timed work is harder to remove.
  3. Read one sample: start.elapsed() prints a single Duration, one sample that says nothing about variance. Repeat it before drawing a conclusion.

Transfer challenge: Wrap the example in a loop of 20 runs, sort the durations, and print the median and the slowest. Then profile the slowest case before changing workload.

Connections

  • Unsafe Traits: Make an implementation promise other unsafe code relies on
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Benchmark & Profile (courseId "systems", lessonId "benchmarking-profiling")
Link: https://crabrix.com/learn/systems/benchmarking-profiling/
Goal: A benchmark measures a stable workload; a profiler explains where its time or allocations go.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/benchmarking-profiling) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.