Skip to content
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

Add benchmarks for u32/u64 functions. #582

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
52 changes: 51 additions & 1 deletion benches/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
#![feature(test, maybe_uninit_uninit_array_transpose)]
extern crate test;

use std::mem::MaybeUninit;
use std::{
mem::{size_of, MaybeUninit},
slice,
};

// Call getrandom on a zero-initialized stack buffer
#[inline(always)]
Expand All @@ -19,6 +22,53 @@ fn bench_fill_uninit<const N: usize>() {
test::black_box(buf);
}

#[bench]
pub fn bench_u32(b: &mut test::Bencher) {
#[inline(never)]
fn inner() -> u32 {
getrandom::u32().unwrap()
}
b.bytes = 4;
b.iter(inner);
}
#[bench]
pub fn bench_u32_via_fill(b: &mut test::Bencher) {
#[inline(never)]
fn inner() -> u32 {
let mut res = MaybeUninit::<u32>::uninit();
let dst: &mut [MaybeUninit<u8>] =
unsafe { slice::from_raw_parts_mut(res.as_mut_ptr().cast(), size_of::<u32>()) };
getrandom::fill_uninit(dst).unwrap();
unsafe { res.assume_init() }
}
b.bytes = 4;
b.iter(inner);
}

#[bench]
pub fn bench_u64(b: &mut test::Bencher) {
#[inline(never)]
fn inner() -> u64 {
getrandom::u64().unwrap()
}
b.bytes = 8;
b.iter(inner);
}

#[bench]
pub fn bench_u64_via_fill(b: &mut test::Bencher) {
#[inline(never)]
fn inner() -> u64 {
let mut res = MaybeUninit::<u64>::uninit();
let dst: &mut [MaybeUninit<u8>] =
unsafe { slice::from_raw_parts_mut(res.as_mut_ptr().cast(), size_of::<u64>()) };
getrandom::fill_uninit(dst).unwrap();
unsafe { res.assume_init() }
}
b.bytes = 8;
b.iter(inner);
}

// We benchmark using #[inline(never)] "inner" functions for two reasons:
// - Avoiding inlining reduces a source of variance when running benchmarks.
// - It is _much_ easier to get the assembly or IR for the inner loop.
Expand Down