当前位置 : 主页 > 网络编程 > c#编程 >

Parallel.For循环与普通for循环的性能比较

来源:互联网 收集:自由互联 发布时间:2023-01-31
一、Parallel.For循环优于For的情况 代码: #region Parallel.For public static void ParallelForTest() { //标准For var dt = DateTime.Now; var rand = new Random(DateTime.Now.Millisecond); for (int i = 0; i 20; i++) { Thread.Sleep(r

一、Parallel.For循环优于For的情况

代码:

        #region Parallel.For
        public static void ParallelForTest()
        {
            //标准For
            var dt = DateTime.Now;
            var rand = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < 20; i++)
            {
                Thread.Sleep(rand.Next(100, 1000));
            }
            var standerTime = (DateTime.Now - dt).TotalMilliseconds;
            Console.WriteLine("標準的for循環,耗時{0}毫秒", standerTime);

            //並行For
            dt = DateTime.Now;
            Parallel.For(0, 20, i =>
            {
                Thread.Sleep(rand.Next(100, 1000));
            });
            var parallelTime = (DateTime.Now - dt).TotalMilliseconds;
            Console.WriteLine("并行的for循環,耗時{0}毫秒", parallelTime);
            Console.WriteLine();
            if (standerTime <= parallelTime)
            {
                Console.WriteLine("----------标准的for循環節省{0}毫秒----------", (parallelTime - standerTime));
            }
            else
            {
                Console.WriteLine("----------并行的for循環節省{0}毫秒----------", (standerTime - parallelTime));
            }
            Console.ReadKey();
        }

        #endregion

运行结果:

二、For循环优于Parallel.For的情况

代码:

        #region For
        public static void ForTest()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Console.WriteLine("Parallel.For");
            ParallelLoopResult result =
            Parallel.For(0, 10000, i =>
            {
                //打印空
                Console.Write("");

            });
            sw.Stop();
            TimeSpan ts2 = sw.Elapsed;
            Console.WriteLine("Parallel.For總共花費{0}ms.", ts2.TotalMilliseconds);

            //簡單的For循環
            Stopwatch sw_Eq = new Stopwatch();
            sw_Eq.Start();
            Console.WriteLine("For");
            for (int i = 0; i < 10000; i++)
            {
                //打印空
                Console.Write("");
            }
            sw_Eq.Stop();
            TimeSpan tssw_Eq = sw_Eq.Elapsed;
            Console.WriteLine("for總共花費{0}ms.", tssw_Eq.TotalMilliseconds);
            Console.ReadKey();
        }
        #endregion

运行结果:

到此这篇关于Parallel.For循环与普通for循环比较的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持自由互联。

上一篇:C#使用RestClient调用WebAPI
下一篇:没有了
网友评论