Avatar ·

How to properly measure code performance in Rust: benchmarking and profiling

Hello, colleagues! I've been writing in Rust for about six months and encountered a problem: I can't properly measure how long my code takes to execute. I tried using std::time::Instant, but the results vary from run to run, especially on small functions. For example, I want to compare two ways of summing a vector: ```rust use std::time::Instant; fn sum_for(v: &[i32]) -> i32 { let mut sum = 0; for x in v { sum += x; } sum } fn sum_iter(v: &[i32]) -> i32 { v.iter().sum() } fn main() { let data = vec![1; 1_000_000]; let start = Instant::now(); let _ = sum_for(&data); println!("for: {:?}", start.elapsed()); let start = Instant::now(); let _ = sum_iter(&data); println!("iter: {:?}", start.elapsed()); } ``` On my laptop