how to benchmark parts within a function?

Viewed 69

I have one complicated function that is doing three different things. I have a benchmark written to evaluate the performance of this function, but I want to know the performance of each thing happening within the function separately. Until now, I am using Instant::now() + printing to measure the performance. But is there another way to do it?

1 Answers

You can use criterion for that. This crate offers a functionality to measure the execution time yourself with Custom Measurements.

Here is a basic usage example:

c.bench_function("middle part", |b| {
        b.iter_custom(|iters| {
            let mut exec_time = Duration::ZERO;

            for i in 0..iters {
                // First part of function
                let start = Instant::now();
                // Middle part of function (which is measured here)
                exec_time += start.elapsed();
                // Last part of function
            }
            exec_time
        });
    });

Obviously you can then switch this up to also benchmark the first and last part of your function.

Related