Testing is like making sure your parachute opens before jumping off a plane. Benchmarking, on the other hand, is like checking if you can run faster than your grandma (or at least not get caught by her slippers). In Rust, testing and benchmarking ensure your code is reliable and performs like a champion!
Writing Tests in Rust
Rust has built-in support for testing using the #[test]
attribute. Let’s write a simple test!
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
}
Explanation:
#[cfg(test)]
ensures the test code runs only when testing.#[test]
marks a function as a test case.assert_eq!(a, b)
checks if values match (fails if they don’t).
Run tests with:
cargo test
Handling Expected Failures
Sometimes, you want a test to fail on purpose. Rust provides should_panic
for this!
#[test]
#[should_panic]
fn test_divide_by_zero() {
let _x = 1 / 0; // Uh-oh!
}
Benchmarking Performance
Rust provides the criterion
crate for benchmarking. First, add this to Cargo.toml
:
[dev-dependencies]
criterion = "0.4"
Then, write a benchmark:
use criterion::{black_box, Criterion, criterion_group, criterion_main};
fn my_function() {
let _x: Vec<i32> = (0..1000).collect();
}
fn benchmark(c: &mut Criterion) {
c.bench_function("my_function", |b| b.iter(|| my_function()));
}
criterion_group!(benches, benchmark);
criterion_main!(benches);
Run benchmarks with:
cargo bench
Conclusion
Testing ensures your code doesn’t explode unexpectedly. Benchmarking helps find slow parts of your code. Both are essential for writing solid, production-ready Rust programs.
So, test your code like a scientist and benchmark it like a speed-obsessed racer!
0 Comments