Benchmarking operations in Rust

Published on Jun 12, 2020 | Updated on Apr 29, 2021

We programmers, are always busy writing code. The choice of the technologies and tools we use are often governed by how well they perform and most importantly, how well they’re known to perform. This is when benchmarking becomes vital.

So here’s a guide on benchmarking code in Rust.

A little spoiler here: I’m the author of the devtimer crate, so I may be a little biased here ;) You can see the source code here on GitHub ↗

First start off by including this in your Cargo.toml file:

devtimer = "3.0.0"

Now let’s say you have a simple application with just a main.rs file, which has the code that needs to be benchmarked. So we have two functions main() and super_complex_op(). We need to benchmark whatever super_complex_op() does. Let’s do this! We’ll run the code 10 times to obtain an average of the running time.

File: main.rs

use devtimer::run_benchmark;
fn main() {
    let result = run_benchmark(10, || {
        // We put in the function name
        // which we need to benchmark
        super_complex_op();
    });
    result.print_stats();
}
fn super_complex_op() {
    // This is our fake, complex and slow operation ;)
    std::thread::sleep(std::time::Duration::from_secs(1));
}

This would print out something like:

Running iter 1 ...
Running iter 2 ...
Running iter 3 ...
Running iter 4 ...
Running iter 5 ...
Running iter 6 ...
Running iter 7 ...
Running iter 8 ...
Running iter 9 ...
Running iter 10 ...

Slowest: 1000124916 ns
Fastest: 1000083916 ns
Average: 1000109859 ns/iter

That’s it? Yes! Isn’t that fantastic? That’s all you do!

To see more of this library’s abilities, check out the very useful docs - right here

I’m also working on a database which I plan to call TerrabaseDB or Skybase (or both as two separate classes of databases) — it’s going to be a lightning fast NoSQL database! (stay tuned)