Summary - Build tools
- Rust course
- Expert
- Lesson 42/46
- 5 min
Combine build.rs, LTO and flamegraph to write a build report.
Build tools summary
build.rs generates code before compilation and instructs the linker; outputs go to OUT_DIR. Cross compilation is done with a target triple, rustup target and a suitable linker. In the release profile, lto, codegen-units, panic and opt-level balance speed, size and build time. Optimization starts with a profile: perf/samply, flamegraph, criterion. Unsafe code is kept sound with // SAFETY: comments, contracts protected by assert!s, and Miri.
A small measurement helper
Measurement code usually calls a job n times and finds the average by dividing the time. A helper that counts calls also verifies that the setup works correctly:
fn olc<F: FnMut()>(n: u32, mut f: F) -> std::time::Duration {
let bas = std::time::Instant::now();
for _ in 0..n {
f();
}
bas.elapsed() / n
}The duration varies on every run; that's why benchmark tools use warm-up rounds and a statistical summary.
Practice Measurement setup
Write fn olc<F: FnMut()>(n: u32, mut f: F) -> u32 that calls a closure n times and returns the call count. Call it 1000 times with a closure incrementing a counter and print it as 1000 çağrı, sayaç 1000.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn olc<F: FnMut()>(n: u32, mut f: F) -> u32 {
for _ in 0..n {
f();
}
n
}
fn main() {
let mut sayac = 0;
let n = olc(1000, || sayac += 1);
println!("{} çağrı, sayaç {}", n, sayac);
}Expected output
1000 çağrı, sayaç 1000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How do you stop the compiler from deleting the work in a simple measurement loop?
- It can't be prevented
- Use the result or pass it through black_box Correct answer
- Build in debug
- Make the loop longer
Explanation: A pure computation whose result is never used can be removed entirely by optimization.
2 Elapsed time
let bas = std::time::Instant::now();
is();
let sure = bas.____();
let bas = std::time::Instant::now();
is();
let sure = bas.elapsed();
Explanation: Instant::elapsed gives the time since the start.
3 Group summary
| Term | Meaning |
|---|---|
build.rs |
Before the build |
--target |
Cross compilation |
lto |
Link-time optimization |
Miri |
UB checking |