usingSystem;usingSystem.Math;namespacepiwithmontecarlo{/// <summary> ///Trivial, synchronous calculation algorithm/// </summary> Public Static classTrivialpicalculator { Public Static DoubleCalculate (intiterations) { intInCircle =0; varRandom =NewRandom (); for(inti =0; I < iterations; i++) { varA =Random. Nextdouble (); varb =Random. Nextdouble (); //strictly speaking, we don't need Sqrt here. We could simply drop it and still get the//same result. However, this sample should demonstrate some perf topics, too. Therefore//It stays there just so the program have to do some math.#ifLang_experimentalvarc = Sqrt (A * a + b *b);#else varc = Math.sqrt (A * a + b *b);#endif if(c <=1) {incircle++; } } return((Double) incircle/iterations) *4; } }}usingSystem;usingSystem.Diagnostics;namespacepiwithmontecarlo.testdriver{classProgram {Static voidMain (string[] args) { variterations =20000000*Environment.processorcount; Executeandprint ("Trivial PI Calculator", Trivialpicalculator.calculate, iterations); Executeandprint ("\ n (Stupid) parallel.for PI Calculator", Parallelforpicalculator.calculate, iterations); Executeandprint ("\nparallel.for PI Calculator", Enhancedparallelforpicalculator.calculate, iterations); Executeandprint ("\nplinq PI Calculator", Plinqpicalculator.calculate, iterations); Executeandprint ("\nfast PI Calculator", Fastpicalculator.calculate, iterations); } Private Static voidExecuteandprint (stringLabel, func<int,Double> Calculation,intiterations) {Console.WriteLine (label); Printresult (Measure ()=calculation (iterations)), iterations); } Private Static voidPrintresult (tuple<Double, Timespan> R,intiterations) {Console.WriteLine ("{0} ({1:#,# #0.0000} sec for {2:#,# #0} iterations = {3:#,# #0. xx} iter/sec)", R.item1, R.item2.totalseconds, iterations, iteration S/r.item2.totalseconds); } Private StaticTuple<t, timespan> measure<t> (func<t>body) { varWatch =NewStopwatch (); Watch. Start (); varresult =body (); Watch. Stop (); return NewTuple<t, timespan>(result, watch.) Elapsed); } }}
More addresses
Http://www.software-architects.com/devblog/2014/09/22/C-Parallel-and-Async-Programming
Sample Code/calculate PI (EXT)