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 a quickly put together Rust version #5

Merged
merged 2 commits into from Oct 12, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
62 changes: 62 additions & 0 deletions primes.rs
@@ -0,0 +1,62 @@
use std::env;
use std::time::{Instant, Duration};

const PRIMES_COUNT: u32 = 10000000;

fn get_primes7(count: u32) -> Vec<u32> {
if count < 2 {
return vec![];
} else if count == 2 {
return vec![2];
}

let mut s = Vec::new();
let mut i = 3;
while i < count+1 {
s.push(i);
i += 2;
}

let mroot = (count as f32).sqrt() as u32;
let half = s.len() as u32;

let mut i: u32 = 0;
let mut m: u32 = 3;

while m <= mroot {
if s.get(i as usize).is_some() && s[i as usize] != 0 {
let mut j = (m*m-3)/2;
s[j as usize] = 0;
while j < half {
s[j as usize] = 0;
j += m;
}
}
i += 1;
m = 2*i+3;
}

let mut res = Vec::new();
res.push(2);
res.extend(s.into_iter().filter(|x| *x != 0));
res
}

fn main() {
let run_time_secs = match env::var("RUN_TIME") {
Ok(v) => match v.parse::<u32>() {
Ok(i) => i,
Err(err) => panic!("RUN_TIME environment variable error: {}", err),
},
Err(err) => panic!("RUN_TIME environment variable error: {}", err),
};

let run_time = Duration::new(run_time_secs as u64, 0);
let start = Instant::now();

while start.elapsed() < run_time {
let primes = get_primes7(PRIMES_COUNT);
println!("Found {} prime numbers.", primes.len());
}
}

6 changes: 6 additions & 0 deletions run.sh
Expand Up @@ -134,3 +134,9 @@ C='nodejs' ; SRC='primes.js' ; run_benchmark 'JavaScript (nodejs)' 'true' "$C $S
##

C='ruby' ; SRC='primes.rb' ; run_benchmark 'Ruby' 'true' "$C $SRC" "$C -v" 'cat' "$SRC"

##

# -C opt-level=3 is the default opt level for the code produced by the --release target.
C='rust'; SRC='primes.rs' ; run_benchmark 'Rust' 'rustc -C opt-level=3 -o primes.rs.out primes.rs' './primes.rs.out' 'rustc -V' 'head -n1' "$SRC"
rm -f primes.rs.out