Skip to content

Instantly share code, notes, and snippets.

@Thomasdezeeuw
Created January 15, 2019 12:55
Show Gist options
  • Save Thomasdezeeuw/e6ce3dac1dd052c21bb84a306df1138b to your computer and use it in GitHub Desktop.
Save Thomasdezeeuw/e6ce3dac1dd052c21bb84a306df1138b to your computer and use it in GitHub Desktop.
Comparing atomic and non-atomic additions in Rust.
// This should be "benches/atomics.rs", but gists can't have subdirectories.
use std::sync::atomic::{AtomicUsize, Ordering};
use criterion::{Criterion, Fun, criterion_group, criterion_main};
fn add1(n: usize) -> usize {
n + 1
}
fn add1_atomic(n: AtomicUsize) -> AtomicUsize {
n.fetch_add(1, Ordering::Relaxed);
n
}
fn benchmark_add(c: &mut Criterion) {
let add = Fun::new("Non atomic", |b, i| b.iter(|| add1(*i)));
let atomic_add = Fun::new("atomic", |b, i| b.iter(|| add1_atomic(AtomicUsize::new(*i))));
c.bench_functions("Add", vec![add, atomic_add], 0);
}
criterion_group!(benches, benchmark_add);
criterion_main!(benches);
[package]
name = "tmp"
version = "0.1.0"
authors = ["Thomas de Zeeuw <thomasdezeeuw@gmail.com>"]
edition = "2018"
[dev-dependencies]
criterion = "0.2"
[[bench]]
name = "atomics"
harness = false
Add/Non atomic time: [336.94 ps 338.56 ps 340.38 ps]
Found 18 outliers among 100 measurements (18.00%)
4 (4.00%) high mild
14 (14.00%) high severe
Add/atomic time: [11.412 ns 11.465 ns 11.523 ns]
Found 13 outliers among 100 measurements (13.00%)
6 (6.00%) high mild
7 (7.00%) high severe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment