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
运行结果:
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/14798391.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。