Skip to content

Instantly share code, notes, and snippets.

@saethlin
Created March 19, 2018 20:41
Show Gist options
  • Save saethlin/b92fe08be85674d9884701bf593a1fc2 to your computer and use it in GitHub Desktop.
Save saethlin/b92fe08be85674d9884701bf593a1fc2 to your computer and use it in GitHub Desktop.
#[macro_use]
extern crate bencher;
extern crate rayon;
use rayon::prelude::*;
use bencher::Bencher;
fn sieve(bench: &mut Bencher) {
bench.iter(|| {
let max = 10_000 as usize;
// This mut is more of an annotation than anything
// It's not required, but we're going to mutate it...
let mut is_prime = vec![true; (max + 1) / 2 as usize];
let mut j_vec = Vec::new();
let mut i = 3;
while i < ((max + 1) as f64).sqrt() as usize {
if is_prime[i / 2] {
let mut j = i * i;
// First we need some data for rayon to iterate over
j_vec.clear();
while j <= max {
j_vec.push(j);
j = j + 2 * i;
}
j_vec.par_iter().for_each(|j| {
// The writes to is_prime probably qualify as a data race, but we don't care!
// No seriously, we don't.
unsafe {
let is_prime_ptr = is_prime.as_ptr() as *mut bool;
*is_prime_ptr.offset((j / 2) as isize) = false;
}
});
}
i += 2
}
})
}
benchmark_group!(benches, sieve);
benchmark_main!(benches);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment