/* * 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}"); }