首页 > 代码库 > C#并行计算一定能提高性能?

C#并行计算一定能提高性能?

        #region 单层循环        public static void CompareSingleCycle()        {            var data = http://www.mamicode.com/Enumerable.Range(0, 100000000).ToArray();"NormalSingleCycle", () => NormalSingleCycle(data));            Timing("ParallelSingleCycle", () => ParallelSingleCycle(data));        }        private static void NormalSingleCycle(int[] data)        {            for (int i = 0; i < data.Length; i++)            {                data[i]++;            }        }        private static void ParallelSingleCycle(int[] data)        {            Parallel.For(0, data.Length, (i) => data[i]++);        }        #endregion        #region 多层循环        public static void CompareMultiCycle()        {            var data = http://www.mamicode.com/Enumerable.Range(0, 100000000).ToArray();"NormalMultiCycle", () => NormalMultiCycle(data));            Timing("ParallelMultiCycle", () => ParallelMultiCycle(data));        }        private static void NormalMultiCycle(int[] data)        {            for (int i = 0; i < data.Length; i++)            {                for (int j = 0; j < 5; j++)                {                    for (int k = 0; k < 5; k++)                    {                        data[i] += j + k;                    }                }            }        }        private static void ParallelMultiCycle(int[] data)        {            Parallel.For(0, data.Length, (i) =>                {                    for (int j = 0; j < 5; j++)                    {                        for (int k = 0; k < 5; k++)                        {                            data[i] += j + k;                        }                    }                });        }        #endregion        private static void Timing(string name, Action action)        {            Stopwatch sw = new Stopwatch();            sw.Start();            action();            sw.Stop();            Console.ForegroundColor = ConsoleColor.Yellow;            Console.WriteLine("【 {0} 】: {1} ms", name, sw.ElapsedMilliseconds);            Console.ResetColor();        }

实际与想象貌似还真的不一样。  

C#并行计算一定能提高性能?