建议88:并行并不总是速度更快
并行所带来的后台任务及任务的管理,都会带来一定的开销,如果一项工作本来就能很快完成,或者说循环体很小,那么并行的速度也许会比非并行要慢。
看这样一个例子,我们比较在同步和并行状态下的时间消耗:
static void Main(string[] args) { Stopwatch watch = new Stopwatch(); watch.Start(); DoInFor(); watch.Stop(); Console.WriteLine("同步耗时:{0}", watch.Elapsed); watch.Restart(); DoInParalleFor(); watch.Stop(); Console.WriteLine("并行耗时:{0}", watch.Elapsed); Console.ReadKey(); } static void DoSomething() { for (int i = 0; i < 10; i++) { i++; } } static void DoInFor() { for (int i = 0; i < 200; i++) { DoSomething(); } } static void DoInParalleFor() { Parallel.For(0, 200, (i) => { DoSomething(); }); } |
以上代码在笔者当前的双核PC机上的输出为:
同步耗时:00:00:00.0005583 并行耗时:00:00:00.0033604 |
可见,同步只用了0.55毫秒,而并行则使用了3.3毫秒才完成工作。
现在,为了模拟让循环体做更多事情,将DoSomething方法中的循环体由10变为10000000。运行的结果为:
同步耗时:00:00:01.3059138 并行耗时:00:00:00.6560593 |
当循环体需要做更多工作的时候,我们发现,同步需要1.3秒才能完成工作,而并行则仅使用0.6秒就完成了工作。
相关链接:
连载1 连载2 连载3 连载4 连载5 连载6 连载7 连载8 连载9
连载10 连载11 连载12 连载13 连载14 连载15 连载71 连载72 连载73
连载74 连载75 连载76 连载77 连载78 连载79 连载80 连载81 连载82
连载83 连载84 连载85 连载86 连载87