Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* threadpi.rs
* Neil Gershenfeld 12/22/24
* Rust threads parallel pi calculation benchmark
* pi = 3.14159265358979323846
*/
use std::thread;
use std::env;
use std::process;
use std::time::SystemTime;
const NPTS:u64 = 1e9 as u64;
fn main() {
let args:Vec<String> = env::args().collect();
if args.len() != 2 {
println!("command line: threadpi.rs number_of_threads");
process::exit(-1);
}
let num_threads:u64 = args[1].parse().unwrap();
let a:f64 = 0.5;
let b:f64 = 0.75;
let c:f64 = 0.25;
let start = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_micros();
let mut handles = Vec::new();
for i in 0..num_threads {
handles.push(
thread::spawn(move || {
let start:u64 = 1+NPTS*i;
let end:u64 = NPTS*(i+1);
let mut partial_pi:f64 =0.0;
for i in start..=end {
partial_pi += a/(((i as f64)-b)*((i as f64)-c));
}
return partial_pi;
}));
}
let mut pi:f64 = 0.0;
for handle in handles {
pi += handle.join().unwrap();
}
let end = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_micros();
let dt = ((end-start) as f64)/1e6;
let mflops = (num_threads as f64)*(NPTS as f64)*5.0/((dt as f64)*1e6);
println!("NPTS = {NPTS}, threads = {num_threads}, pi = {pi}");
println!("time = {dt:.3}, estimated MFlops = {mflops:.0}");
}