Skip to content

Instantly share code, notes, and snippets.

@llogiq
Last active August 29, 2015 14:25
Show Gist options
  • Save llogiq/5aaa21a0737eef8bf0af to your computer and use it in GitHub Desktop.
Save llogiq/5aaa21a0737eef8bf0af to your computer and use it in GitHub Desktop.
Microbenchmark of the fannkuch_redux' rotate method
#![feature(test)]
extern crate test;
use std::mem;
use std::intrinsics::copy;
fn rotate(x: &mut [i32]) {
let mut prev = x[0];
for place in x.iter_mut().rev() {
prev = mem::replace(place, prev)
}
}
fn rotate_new(x: &mut [i32]) {
let tmp = x[0];
let last = x.len() - 1;
if last <= 0 { return; }
unsafe { copy(&x[1], &mut x[0], last); }
x[last] = tmp;
}
fn rotate_bench(data: &mut [i32], bench: &mut test::Bencher) {
bench.iter(|| {
rotate(data);
test::black_box(data[0]);
});
}
fn rotate_new_bench(data: &mut [i32], bench: &mut test::Bencher) {
bench.iter(|| {
rotate_new(data);
test::black_box(data[0]);
});
}
fn test_same(old: &mut [i32], new: &mut [i32]) {
assert_eq!(old, new);
rotate(old);
rotate_new(new);
assert_eq!(old, new);
}
#[test]
fn test_rotate_16() {
let mut x = [1i32; 16];
let mut y = [1i32; 16];
for i in (0i32..16) {
x[i as usize] = i;
y[i as usize] = i;
}
test_same(&mut x, &mut y);
}
#[test]
fn test_rotate_1() {
let mut x = [1];
let mut y = [1];
test_same(&mut x, &mut y);
}
#[bench]
fn bench_rotate_16(bench: &mut test::Bencher) {
let mut x = [1i32; 16];
for i in (0i32..16) { x[i as usize] = i; }
rotate_bench(&mut x, bench);
}
#[bench]
fn bench_rotate_16_new(bench: &mut test::Bencher) {
let mut x = [1i32; 16];
for i in (0i32..16) { x[i as usize] = i; }
rotate_new_bench(&mut x, bench);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment