【示例代码】 Tuple<T> Func<T>

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

 

posted @ 2016-03-31 17:24  小泥巴2008  阅读(305)  评论(0编辑  收藏  举报