为什么在这个例子中并行版本比顺序版本慢? [英] Why was the parallel version slower than the sequential version in this example?
问题描述
最近几天我一直在学习一些关于并行性的知识,我遇到了 这个 例子.
I've been learning a little about parallelism in the last few days, and I came across this example.
我将它与这样的顺序 for 循环并排放置:
I put it side to side with a sequential for loop like this:
private static void NoParallelTest()
{
int[] nums = Enumerable.Range(0, 1000000).ToArray();
long total = 0;
var watch = Stopwatch.StartNew();
for (int i = 0; i < nums.Length; i++)
{
total += nums[i];
}
Console.WriteLine("NoParallel");
Console.WriteLine(watch.ElapsedMilliseconds);
Console.WriteLine("The total is {0}", total);
}
我惊讶地发现 NoParallel 方法的完成速度比网站上给出的并行示例快得多.
I was surprised to see that the NoParallel method finished way way faster than the parallel example given at the site.
我有一台 i5 电脑.
I have an i5 PC.
我真的认为 Parallel 方法会完成得更快.
I really thought that the Parallel method would finish faster.
对此有合理的解释吗?也许我误解了什么?
Is there a reasonable explanation for this? Maybe I misunderstood something?
推荐答案
顺序版本更快,因为在您的示例中,在每次迭代上执行操作所花费的时间非常少,并且创建和管理多个操作涉及相当大的开销线程.
The sequential version was faster because the time spent doing operations on each iteration in your example is very small and there is a fairly significant overhead involved with creating and managing multiple threads.
并行编程仅在每次迭代在处理器时间方面足够昂贵时才能提高效率.
Parallel programming only increases efficiency when each iteration is sufficiently expensive in terms of processor time.
这篇关于为什么在这个例子中并行版本比顺序版本慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!