I am new to Rust and am trying to benchmark sorting algorithms.
The functions take immutable references to a slice (fn sort(&self, slice: &mut [T])
).
I am trying to use the criterion
crate to benchmark them for different inputs (random vectors of increasing length).
However I cannot figure out how to pass the vectors to the functions as mutable references. I have tried the the fixes suggested by rustc
but each generates another error.
The benchmark code is (shortened example to exclude all the functions):
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use rand::{distributions::Uniform, Rng};
use sorting::*;
fn sorting_benchmarks(c: &mut Criterion) {
let mut group = c.benchmark_group("Sorting");
for i in [1, 10, 100].iter() {
let mut rng = rand::thread_rng();
let range = Uniform::new(0, 100);
let nums: Vec<usize> = (0..(*i)).map(|_| rng.sample(&range)).collect();
let mut v = black_box(nums.to_vec());
group.bench_with_input(BenchmarkId::new("Bubble Sort {}", i), &v, |b, v| {
b.iter(|| BubbleSort.sort(v))
});
group.finish();
}
The function for BubbleSort.sort
is:
impl<T> Sorter<T> for BubbleSort {
fn sort(&self, arr: &mut [T])
where
T: Ord,
{
let mut swapped = true;
while swapped {
swapped = false;
for i in 1..arr.len() {
if arr[i - 1] > arr[i] {
arr.swap(i - 1, i);
swapped = true;
}
}
}
}
}
Some examples of the error messages.
First:
error[E0596]: cannot borrow `v` as mutable, as it is not declared as mutable
--> benches/criterion_bench.rs:16:39
|
15 | group.bench_with_input(BenchmarkId::new("Bubble Sort {}", i), &v, |b, v| {
| - help: consider changing this to be mutable: `mut v`
16 | b.iter(|| BubbleSort.sort(&mut v))
| ^^^^^^ cannot borrow as mutable
If I do the suggested fix, I still get cannot borrow as mutable
.
I have successfully benchmarked the functions using bench_function
from the criterion
crate. But this does not help me with benchmarking against multiple inputs for comparison.