在此示例中,为什么并行版本比顺序版本慢? [英] Why was the parallel version slower than the sequential version in this example?

查看:92
本文介绍了在此示例中,为什么并行版本比顺序版本慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近几天我一直在学习有关并行性的知识,并且遇到了

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电脑.

我真的以为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆