Using System; using System. collections. generic; using System. text; using System. diagnostics; using System. threading; namespace Pi {class Program {static void Main (string [] args) {double pi_wy, sum_wy = 0.0, seri_t_wy, para_t_wy; Stopwatch stopwatch = new Stopwatch (); pi_Thread ParallelOne = new Pi_Thread (1); ThreadStart StartOne = new ThreadStart (ParallelOne. pi_paral); Thread newThreadOne = new Thread (StartOne); Pi_Thread threadTwo = new Pi_Thread (2); ThreadStart StartTwo = new ThreadStart (threadTwo. pi_paral); Thread newThreadTwo = new Thread (StartTwo); stopwatch. start (); newThreadOne. start (); newThreadTwo. start (); newThreadOne. join (); newThreadTwo. join (); stopwatch. stop (); TimeSpan wy_timeSpan_paral = stopwatch. elapsed; sum_wy = ParallelOne. sum + threadTwo. sum; pi_wy = ParallelOne. step * sum_wy; para_t_wy = wy_timeSpan_paral.TotalMilliseconds; Console. writeLine ("parallel Result:" + pi_wy); Console. writeLine ("parallel time:" + para_t_wy); Pi_Thread SerilThread = new Pi_Thread (1); stopwatch. start (); SerilThread. pi_seril (); stopwatch. stop (); TimeSpan wy_timeSpan_seril = stopwatch. elapsed; pi_wy = SerilThread. step * SerilThread. sum; seri_t_wy = wy_timeSpan_seril.TotalMilliseconds-para_t_wy; Console. writeLine ("parallel Result:" + pi_wy); Console. writeLine ("parallel time:" + seri_t_wy); Console. writeLine ("Acceleration ratio:" + seri_t_wy/para_t_wy); Console. read () ;}} class Pi_Thread {int start_wy; int num_steps_wy = 100000000; public double step, x, sum = 0.0; public Pi_Thread (int start) {this. start_wy = start;} public void Pi_paral () {int I; step = 1.0/(double) num_steps_wy; for (I = start_wy; I <= num_steps_wy; I + = 2) {x = (I + 0.5) * step; sum = sum + 4.0/(1.0 + x * x) ;}} public void Pi_seril () {int I; step = 1.0/(double) num_steps_wy; for (I = 1; I <= num_steps_wy; I ++) {x = (I + 0.5) * step; sum = sum + 4.0/(1.0 + x * x );}}}
Parallel result: 3.141592633590 parallel time: 550.5775 parallel result: 3.141592633590 parallel time: 1068.3712 acceleration ratio: 1.94045561251595