Parallel.For循环与普通for循环的性能比较
作者:農碼一生
这篇文章介绍了Parallel.For循环与普通for循环的性能比较,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、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循环比较的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。