Skip to content

add benchmark comparing unsafe version #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: removeUnsafe
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,10 @@ edition = "2021"

[dev-dependencies]
quickcheck = "0.6"
criterion = "0.4.0"
rand = "0.8.5"

[[bench]]
name = "benches"
harness = false
path="benches/benches.rs"
58 changes: 58 additions & 0 deletions benches/benches.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
extern crate arrayref;

use arrayref::array_ref;
use criterion::{criterion_group, criterion_main, Criterion, black_box};
use rand::{Rng, SeedableRng};

pub fn array_refs_random_data(c: &mut Criterion) {
let x = [0,1,2,3,4,5,6,7,8,9];
c.bench_function("Simple bench", |b| {
b.iter(|| {
let a = black_box(array_ref!(x, 0, 5));
let a = black_box(array_ref!(x, 5, 5));
})
});

c.bench_function("Simple bench unsafe", |b| {
b.iter(|| {
let a = black_box(array_ref_unsafe!(x, 0, 5));
let a = black_box(array_ref_unsafe!(x, 5, 5));
})
});

let x = [0u8; (1usize << 20) - 1];
c.bench_function("large array bench", |b| {
b.iter(|| {
let a = black_box(array_ref!(x, 0, 10001));
let a = black_box(array_ref!(x, 10001, 999999));
})
});

c.bench_function("large array bench unsafe", |b| {
b.iter(|| {
let a = black_box(array_ref_unsafe!(x, 0, 10001));
let a = black_box(array_ref_unsafe!(x, 10001, 999999));
})
});
}

criterion_group!(benches, array_refs_random_data);
criterion_main!(benches);

#[macro_export]
macro_rules! array_ref_unsafe {
($arr:expr, $offset:expr, $len:expr) => {{
{
#[inline]
unsafe fn as_array<T>(slice: &[T]) -> &[T; $len] {
&*(slice.as_ptr() as *const [_; $len])
}
let offset = $offset;
let slice = & $arr[offset..offset + $len];
#[allow(unused_unsafe)]
unsafe {
as_array(slice)
}
}
}}
}