Add Go and Rust algorithm benchmarks

This commit is contained in:
2026-11-23 06:57:31 +08:00
commit f026a77a11
14 changed files with 2101 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "algorithmbench"
version = "0.1.0"
+4
View File
@@ -0,0 +1,4 @@
[package]
name = "algorithmbench"
version = "0.1.0"
edition = "2021"
+210
View File
@@ -0,0 +1,210 @@
use std::{env, time::Instant};
struct Rng(u32);
impl Rng {
fn next(&mut self) -> u32 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
self.0 = x;
x
}
}
fn merge_sort(values: &mut [u32], scratch: &mut [u32]) {
let (mut src, mut dst) = (&mut *values, scratch);
let mut width = 1;
let mut in_scratch = false;
while width < src.len() {
for lo in (0..src.len()).step_by(2 * width) {
let mid = (lo + width).min(src.len());
let hi = (lo + 2 * width).min(src.len());
let (mut left, mut right, mut out) = (lo, mid, lo);
while left < mid && right < hi {
if src[left] <= src[right] {
dst[out] = src[left];
left += 1;
} else {
dst[out] = src[right];
right += 1;
}
out += 1;
}
let left_end = out + mid - left;
dst[out..left_end].copy_from_slice(&src[left..mid]);
dst[left_end..hi].copy_from_slice(&src[right..hi]);
}
std::mem::swap(&mut src, &mut dst);
in_scratch = !in_scratch;
width *= 2;
}
if in_scratch {
dst.copy_from_slice(src);
}
}
fn radix_sort(values: &mut [u32], scratch: &mut [u32]) {
let (mut src, mut dst) = (values, scratch);
for shift in [0, 8, 16, 24] {
let mut offsets = [0; 256];
for &value in src.iter() {
offsets[((value >> shift) & 255) as usize] += 1;
}
let mut next = 0;
for offset in &mut offsets {
let count = *offset;
*offset = next;
next += count;
}
for &value in src.iter() {
let bucket = ((value >> shift) & 255) as usize;
dst[offsets[bucket]] = value;
offsets[bucket] += 1;
}
std::mem::swap(&mut src, &mut dst);
}
}
fn bfs(edges: &[u32], distance: &mut [u32], queue: &mut [u32]) {
let (mut head, mut tail) = (0, 1);
queue[0] = 0;
distance[0] = 0;
while head < tail {
let vertex = queue[head] as usize;
head += 1;
for &next in &edges[vertex * 4..vertex * 4 + 4] {
let index = next as usize;
if distance[index] == u32::MAX {
distance[index] = distance[vertex] + 1;
queue[tail] = next;
tail += 1;
}
}
}
}
fn find(parent: &mut [u32], mut x: u32) -> u32 {
while parent[x as usize] != x {
parent[x as usize] = parent[parent[x as usize] as usize];
x = parent[x as usize];
}
x
}
fn union_all(parent: &mut [u32], size: &mut [u32], pairs: &[u32]) {
for pair in pairs.chunks_exact(2) {
let (mut a, mut b) = (find(parent, pair[0]), find(parent, pair[1]));
if a == b {
continue;
}
if size[a as usize] < size[b as usize] {
std::mem::swap(&mut a, &mut b);
}
parent[b as usize] = a;
size[a as usize] += size[b as usize];
}
}
fn checksum(values: &[u32]) -> u64 {
values.iter().fold(14695981039346656037, |hash, &value| {
(hash ^ u64::from(value)).wrapping_mul(1099511628211)
})
}
enum Workload {
Sort(Vec<u32>),
Radix(Vec<u32>),
Bfs(Vec<u32>),
Dsu(Vec<u32>),
}
impl Workload {
fn new(name: &str, n: usize, seed: u32) -> Self {
let mut rng = Rng(seed);
match name {
"sort-random" => Self::Sort((0..n).map(|_| rng.next()).collect()),
"sort-sorted" => Self::Sort((0..n as u32).collect()),
"radix-random" => Self::Radix((0..n).map(|_| rng.next()).collect()),
"radix-sorted" => Self::Radix((0..n as u32).collect()),
"bfs-random" | "bfs-local" => {
let mut edges = Vec::with_capacity(n * 4);
for i in 0..n {
edges.push(((i + 1) % n) as u32);
if name == "bfs-local" {
edges.extend((2..=4).map(|offset| ((i + offset) % n) as u32));
} else {
edges.extend((0..3).map(|_| rng.next() % n as u32));
}
}
Self::Bfs(edges)
}
"dsu" => Self::Dsu((0..n * 4).map(|_| rng.next() % n as u32).collect()),
_ => panic!("unknown workload"),
}
}
fn prepare(&self, a: &mut [u32], b: &mut [u32]) {
match self {
Self::Sort(input) | Self::Radix(input) => a.copy_from_slice(input),
Self::Bfs(_) => {
a.fill(u32::MAX);
b.fill(0);
}
Self::Dsu(_) => {
for (i, parent) in a.iter_mut().enumerate() {
*parent = i as u32;
}
b.fill(1);
}
}
}
fn run(&self, a: &mut [u32], b: &mut [u32]) {
match self {
Self::Sort(_) => merge_sort(a, b),
Self::Radix(_) => radix_sort(a, b),
Self::Bfs(edges) => bfs(edges, a, b),
Self::Dsu(pairs) => union_all(a, b, pairs),
}
}
fn result(&self, a: &mut [u32], b: &mut [u32]) -> u64 {
if let Self::Dsu(_) = self {
for (i, root) in b.iter_mut().enumerate() {
*root = find(a, i as u32);
}
return checksum(b);
}
checksum(a)
}
}
fn main() {
let args: Vec<_> = env::args().collect();
assert_eq!(args.len(), 5, "usage: bench CASE N SEED WARMUPS");
let n: usize = args[2].parse().expect("invalid size");
let seed: u32 = args[3].parse().expect("invalid seed");
let warmups: usize = args[4].parse().expect("invalid warmup count");
assert!(
(1..=10_000_000).contains(&n) && seed != 0,
"invalid input parameters"
);
let workload = Workload::new(&args[1], n, seed);
let (mut a, mut b) = (vec![0; n], vec![0; n]);
for _ in 0..warmups {
workload.prepare(&mut a, &mut b);
workload.run(&mut a, &mut b);
std::hint::black_box((&a, &b));
}
workload.prepare(&mut a, &mut b);
let start = Instant::now();
workload.run(&mut a, &mut b);
let elapsed = start.elapsed().as_nanos();
println!(
r#"{{"nanos":{},"checksum":"{:x}"}}"#,
elapsed,
workload.result(&mut a, &mut b)
);
}