In this lesson, you will learn how to verify that your Rust compiler is generating machine code that satisfies strict performance constraints by inspecting the raw assembly output.
When working with specialized runtime targets—like bare-metal microcontrollers or high-performance Wasm runtimes—it is not enough to trust that your source code is "fast." You must ensure that the compiler's optimizations, such as loop unrolling or SIMD vectorization, are actually applied to your critical paths.
Using cargo-show-asm
The most effective way to audit your code is by using cargo-show-asm. Instead of guessing what the backend produces, you can inspect the generated instruction stream directly.
Consider a function designed to be a tight loop:
#[inline(never)]
pub fn compute_sum(data: &[u32]) -> u32 {
data.iter().sum()
}
If this function sits inside a real-time scheduling loop, you need to verify it isn't making unnecessary stack allocations or function calls. By running cargo asm --lib compute_sum, you can see the assembly equivalent.
What to Look For
When inspecting the output, look for "hidden" overhead that violates your performance budget:
- Branch Predictability: Look for excessive conditional jumps (
je,jne) inside hot loops. If the compiler hasn't flattened these into constant-time instructions (likecmov), your execution time may fluctuate based on input data. - Spills and Fills: Check for
movinstructions involving the stack pointer (rsporsp). Excessive stack access indicates the compiler ran out of registers, which can devastate performance in cycle-sensitive routines. - Unexpected Bloat: If you see calls to
core::panickinginside what should be a "no-panic" hot path, the compiler is generating bounds checks that you might need to optimize away usingget_uncheckedor specialized assertions.
By correlating Rust source lines with assembly blocks, you can identify where abstractions like iterators fail to compile down to raw, pointer-incrementing loops, allowing you to refactor for predictable, low-latency execution.
Key Takeaway: Rust-to-assembly inspection bridges the gap between high-level safety and machine-level predictability, allowing you to prove that your runtime performance meets its worst-case execution time requirements.