为什么此并行代码比其类似的非并行版本慢? [英] Why is this parallel code slower than its similar non parallel version?
问题描述
我有以下代码(从LINQPad复制到这里).显然,我似乎不了解TPL的工作原理或代码是垃圾,为什么并行版本比非并行版本运行速度慢?
I have the following code (copied here from LINQPad). Obviously it looks like I am not understanding how TPL works or the code is garbage, why does the parallel version run slower than its non-parallel counterpart?
for (int i = 0; i < 100; i++)
{
ParallelOptions ops = new ParallelOptions();
ops.MaxDegreeOfParallelism = Environment.ProcessorCount;
var watch = Stopwatch.StartNew();
Parallel.ForEach<int>(Enumerable.Range(1, 10000000), ops, x => { int y = x + 1; });
watch.Stop();
Console.WriteLine("Parallel: {0}", watch.Elapsed.TotalSeconds);
watch = Stopwatch.StartNew();
foreach (var x in Enumerable.Range(1, 10000000))
{
int y = x + 1;
}
watch.Stop();
Console.WriteLine("Non-parallel: {0}\n", watch.Elapsed.TotalSeconds);
}
前10个结果:
平行:0.1991644 非平行:0.0466178
Parallel: 0.1991644 Non-parallel: 0.0466178
平行:0.1723428 非平行:0.0447134
Parallel: 0.1723428 Non-parallel: 0.0447134
平行度:0.1141791 非平行:0.0444557
Parallel: 0.1141791 Non-parallel: 0.0444557
平行:0.1758878 非平行:0.0444636
Parallel: 0.1758878 Non-parallel: 0.0444636
平行:0.1687637 非平行:0.0444338
Parallel: 0.1687637 Non-parallel: 0.0444338
平行度:0.1677679 非平行:0.0445771
Parallel: 0.1677679 Non-parallel: 0.0445771
平行:0.1191462 非平行:0.0446116
Parallel: 0.1191462 Non-parallel: 0.0446116
平行:0.1702483 非平行:0.0454863
Parallel: 0.1702483 Non-parallel: 0.0454863
平行:0.1143605 非平行:0.0451731
Parallel: 0.1143605 Non-parallel: 0.0451731
平行:0.2155218 非平行:0.0450392
Parallel: 0.2155218 Non-parallel: 0.0450392
推荐答案
好吧,您可以获得的最佳答案是运行一个探查器工具并测量代码的运行状况.但是我有根据的猜测是,并行代码的速度较慢,因为您的代码非常简单,以至于启动线程和在线程之间进行切换会增加大量成本,因此计算速度上的任何优势都可以忽略不计.
Well, the best answer you can get is to run a profiler tool and measure what is going on with your code. But my educated guess is that your parallel code is slower because your code is so simple that starting up threads and switching between them add up so much cost that any advantage in the calculation speed is negligible.
但是尝试进行一些实质性的计算,最终您将具有并行执行的优势.您的代码太简单了.现代的CPU不能以这种方式加载.
But try to make some substantial computations and you eventually will have the parallel execution advantage. Your code is too simple. Modern CPUs are not to be loaded in this way.
这篇关于为什么此并行代码比其类似的非并行版本慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!