码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2014-10-22 17:13:39      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:blog   color   io   ar   for   div   on   art   cti   

        #region 单层循环
        public static void CompareSingleCycle()
        {
            var data = Enumerable.Range(0, 100000000).ToArray();
            Timing("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 = Enumerable.Range(0, 100000000).ToArray();
            Timing("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#并行计算一定能提高性能?

标签:blog   color   io   ar   for   div   on   art   cti   

原文地址:http://www.cnblogs.com/vvolf/p/4043382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!