Parallel.For循环与普通for循环的性能比较
时间:2022-11-20 10:13:05|栏目:.NET代码|点击: 次
一、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
运行结果:
上一篇:解决 .NET Core 中 GetHostAddressesAsync 引起的 EnyimMemcached 死锁问题
栏 目:.NET代码
下一篇:关于Swagger优化的实战记录
本文标题:Parallel.For循环与普通for循环的性能比较
本文地址:http://www.codeinn.net/misctech/219428.html