Last active
February 27, 2022 09:25
-
-
Save JmPotato/b8bd32c96722ad42cdbab4bb75f7429e to your computer and use it in GitHub Desktop.
sort_unstable_benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(sort_internals)] | |
use std::{ | |
fs::OpenOptions, | |
io::{Read, Write}, | |
path::Path, | |
}; | |
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; | |
use rand::{rngs::StdRng, Rng, SeedableRng}; | |
const MAX_LEN: usize = 600; | |
fn read_or_generate_input(len: usize, modulus: i32) -> [i32; MAX_LEN] { | |
let mut input = vec![0; MAX_LEN]; | |
let file_path_str = String::from(format!("input_{}_{}", len, modulus).as_str()); | |
let file_path = Path::new(file_path_str.as_str()); | |
if file_path.exists() { | |
let mut file = OpenOptions::new().read(true).open(file_path).unwrap(); | |
let mut buf = [0; 8 + MAX_LEN * 4]; | |
file.read(&mut buf).unwrap(); | |
input = bincode::deserialize(&buf[..]).unwrap(); | |
} else { | |
let mut new_file = OpenOptions::new() | |
.read(true) | |
.write(true) | |
.create_new(true) | |
.open(file_path) | |
.unwrap(); | |
let mut rng = StdRng::from_entropy(); | |
for i in 0..len { | |
input[i] = rng.gen::<i32>() % modulus; | |
} | |
let encoded: Vec<u8> = bincode::serialize(&input).unwrap(); | |
new_file.write_all(&encoded).unwrap(); | |
} | |
input.try_into().unwrap_or_else(|v: Vec<i32>| { | |
panic!( | |
"Expected a Vec of length {} but it was {}", | |
MAX_LEN, | |
v.len() | |
) | |
}) | |
} | |
fn sort_unstable(v: &[i32], tmp: &mut [i32]) { | |
// Sort in default order. | |
tmp.copy_from_slice(v); | |
tmp.sort_unstable(); | |
// Sort in ascending order. | |
tmp.copy_from_slice(v); | |
tmp.sort_unstable_by(|a, b| a.cmp(b)); | |
// Sort in descending order. | |
tmp.copy_from_slice(v); | |
tmp.sort_unstable_by(|a, b| b.cmp(a)); | |
} | |
fn benchmark_sort_unstable(c: &mut Criterion) { | |
for len in [25, 500] { | |
for modulus in [5, 10, 100, 1000] { | |
let v = read_or_generate_input(len, modulus); | |
let mut tmp = [0; MAX_LEN]; | |
c.bench_with_input( | |
BenchmarkId::new( | |
"sort_unstable", | |
format!("length: {}, modulus: {}", len, modulus), | |
), | |
&len, | |
|b, _| b.iter(|| sort_unstable(&v[0..len], &mut tmp[0..len])), | |
); | |
} | |
} | |
} | |
criterion_group!(benches, benchmark_sort_unstable); | |
criterion_main!(benches); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment