为什么C#Parallel.Invoke是慢? [英] Why C# Parallel.Invoke is slow?

查看:456
本文介绍了为什么C#Parallel.Invoke是慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样做:

    private static void Main(string[] args)
    {
        var dict1 = new Dictionary<int, string>();
        var dict2 = new Dictionary<int, string>();
        DateTime t1 = DateTime.Now;
        for (int i = 1; i < 1000000; i++)
        {
            Parallel.Invoke(
                  () => dict1.Add(i, "Test" + i), 
                  () => dict2.Add(i, "Test" + i) );
        }
        TimeSpan t2 = DateTime.Now.Subtract(t1);

        Console.WriteLine(t2.TotalMilliseconds);

        Console.ReadLine();
    }



所以,做一个for循环百万时间和添加项目到两个不同的字典。
中的问题是,它需要11秒这超过5时的正常顺序方法(无任务/线程)其中只需要2秒。
不知道为什么。

So doing a for loop 1 million time and adding items to two different dictionaries. The problem is that it takes 11 secs which is more than 5 time the normal sequential method (without tasks/threads) which takes only 2 sec. Don't know why.

推荐答案

像其他人所说的或隐含的并行代码并不总是更快,因为并行的开销。

Like others have said or implied, parallel code is not always faster due to the overhead of parallelization.

话虽这么说,你的代码的添加项目并联1M次2字典的,而你应该是添加1M项目2字典并行的。所不同的是微妙的,但最终的结果是代码,是〜比你的顺序的情况下快10%(在我的机器上)。

That being said, your code is adding an item to 2 dictionaries in parallel 1M times while you should be adding 1M items to 2 dictionaries in parallel. The difference is subtle but the end result is code that is ~10% faster (on my machine) than your sequential case.

Parallel.Invoke(() => FillDictionary(dict1, 1000000), () => FillDictionary(dict2, 1000000));

...

private static void FillDictionary(Dictionary<int, string> toFill, int itemCount)
{
    for(int i = 0 ; i < itemCount; i++)
        toFill.Add(i, "test" + i);
}

这篇关于为什么C#Parallel.Invoke是慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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