1. 程式人生 > >並行效能分析

並行效能分析

class Program
    {
        static void Main(string[] args)
        {
            List<entityA> source = new List<entityA>();
            for (int i = 0; i < 20; i++)
            {
                source.Add(new entityA
                {
                    name = "悟空" + i,
                    sex 
= i % 2 == 0 ? "" : "", age = i }); } Stopwatch Watch3 = new Stopwatch(); Watch3.Start(); loop2(source); Watch3.Stop(); Console.WriteLine("一般foreach迴圈耗時:" + Watch3.ElapsedMilliseconds); Stopwatch Watch5
= new Stopwatch(); Watch5.Start(); loop4(source); Watch5.Stop(); Console.WriteLine("並行foreach迴圈耗時:" + Watch5.ElapsedMilliseconds); Console.ReadLine(); } //普通的foreach迴圈 static void loop2(List<entityA> source) {
foreach (entityA item in source) { item.age = +10; System.Threading.Thread.Sleep(3);//毫秒 } } //並行的foreach迴圈 static void loop4(List<entityA> source) { Parallel.ForEach(source,new ParallelOptions { MaxDegreeOfParallelism=Environment.ProcessorCount}, item => { item.age = item.age + 10; System.Threading.Thread.Sleep(3); }); } // 0 1 2 5 10 100 500 10000 10000 Environment.ProcessorCount*4 10000 Environment.ProcessorCount*2 //一般foreach迴圈耗時 0 38 58 119 218 2011 10000 20010 20010 20008 //並行foreach迴圈耗時 97 84 65 68 92 564 2500 5080 4055 4087 } //簡單的實體 class entityA { public string name { set; get; } public string sex { set; get; } public int age { set; get; } }

2毫秒以上可以用並行