Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
extern crate rayon;
use rayon::prelude::*;
use std::time::Instant;
fn collatz(mut x: u64) -> usize {
let mut steps = 0;
while x != 1 {
if x % 2 == 0 {
x /= 2;
} else {
x = 3*x + 1;
}
steps += 1;
}
return steps;
}
fn imperative(upper_limit: u64) -> (u64, usize) {
let mut champion: u64 = 0;
let mut max_steps: usize = 0;
for i in 1 .. upper_limit {
let steps = collatz(i);
if steps > max_steps {
champion = i;
max_steps = steps;
}
}
return (champion, max_steps);
}
fn serial(upper_limit: u64) -> (u64, usize) {
(1 .. upper_limit)
.into_iter()
.map(|i| (i, collatz(i)))
.max_by(|a, b| (a.1).cmp(&b.1))
.unwrap()
}
fn parallel(upper_limit: u64) -> (u64, usize) {
(1 .. upper_limit)
.into_par_iter()
.map(|i| (i, collatz(i)))
.max_by(|a, b| (a.1).cmp(&b.1))
.unwrap()
}
fn main() {
let top = Instant::now();
let result = imperative(1_000_000);
let elapsed = top.elapsed();
println!("Imperative: {:?}: {}.{:09}s", result, elapsed.as_secs(), elapsed.subsec_nanos());
let top = Instant::now();
let result = serial(1_000_000);
let elapsed = top.elapsed();
println!("Serial : {:?}: {}.{:09}s", result, elapsed.as_secs(), elapsed.subsec_nanos());
let top = Instant::now();
let result = parallel(1_000_000);
let elapsed = top.elapsed();
println!("Parallel : {:?}: {}.{:09}s", result, elapsed.as_secs(), elapsed.subsec_nanos());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.