sample code /calculate PI (转)
Posted 小泥巴文档
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sample code /calculate PI (转)相关的知识,希望对你有一定的参考价值。
using System; using System.Math; namespace PiWithMonteCarlo { /// <summary> /// Trivial, synchronous calculation algorithm /// </summary> public static class TrivialPiCalculator { public static double Calculate(int iterations) { int inCircle = 0; var random = new Random(); for (int i = 0; i < iterations; i++) { var a = random.NextDouble(); var b = random.NextDouble(); // Strictly speaking, we do not 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 has to do some math. #if LANG_EXPERIMENTAL var c = Sqrt(a * a + b * b); #else var c = Math.Sqrt(a * a + b * b); #endif if (c <= 1) { inCircle++; } } return ((double)inCircle / iterations) * 4; } } } using System; using System.Diagnostics; namespace PiWithMonteCarlo.TestDriver { class Program { static void Main(string[] args) { var iterations = 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 void ExecuteAndPrint(string label, Func<int, double> calculation, int iterations) { Console.WriteLine(label); PrintResult(Measure(() => calculation(iterations)), iterations); } private static void PrintResult(Tuple<double, TimeSpan> r, int iterations) { Console.WriteLine( "{0} ({1:#,##0.0000} sec for {2:#,##0} iterations = {3:#,##0.00} iter/sec)", r.Item1, r.Item2.TotalSeconds, iterations, iterations / r.Item2.TotalSeconds); } private static Tuple<T, TimeSpan> Measure<T>(Func<T> body) { var watch = new Stopwatch(); watch.Start(); var result = body(); watch.Stop(); return new Tuple<T, TimeSpan>(result, watch.Elapsed); } } }
更多地址
http://www.software-architects.com/devblog/2014/09/22/C-Parallel-and-Async-Programming
以上是关于sample code /calculate PI (转)的主要内容,如果未能解决你的问题,请参考以下文章
redux sample with redux source code
Practise Site Home Sample Page Codes de carte cadeau Amazon | Codes Promo Amazon