Measure how much time your function is taking in Rust
One of the ways to benchmark your code in Rust
To optimize our code, we need to measure the performance of our code. One of the ways to measure performance of the code(Compute intensive) is to measure the time taken by the code to execute.
Here is one of the simplest ways to measure the time it takes to execute your function in Rust.
Create a new project using cargo new command.
cargo new benchmarksimpleEdit the main.rs file inside the src folder.
use std::time::Instant;
fn main() {
let now = Instant::now();
sum_large();
let elapsed = now.elapsed();
println!("Elapsed: {:.2?}", elapsed);
}
fn sum_large() -> u64 {
let mut sum: u64 = 0;
for i in 1..10000001 {
sum += i;
}
sum
}Execute your code using cargo run command.
PS C:\crown\benchmarksimple> cargo run Compiling benchmarksimple v0.1.0 (C:\crown\benchmarksimple) Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.52s Running `target\debug\benchmarksimple.exe` Elapsed: 53.25ms PS C:\crown\benchmarksimple> cargo run Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s Running `target\debug\benchmarksimple.exe` Elapsed: 56.74ms
There are crates like criterion which can be used with many more functionalities. We will review them in future posts.
Thanks for reading!

