【问题标题】:Nested Parallel.For loop performance and Large Lists嵌套 Parallel.For 循环性能和大型列表
【发布时间】:2016-10-12 22:30:44
【问题描述】:

我正在执行的代码有一个简单的功能。它将元组 (Tuple<int, int, BigInteger>) 的前 2 项与另一个进行比较,并确定所有条目是否不同。如果是,则形成一个组合元组 (Tuple<int, int, int, int BigInteger>) 并将其添加到 List<Tuple<int, int, int, int, BigInteger>>

例子:

    Tuple<int, int, BigInteger> example1 = new Tuple<int, int BigInteger>(5, 6, 1000);
    Tuple<int, int, BigInteger> example2 = new Tuple<int, int BigInteger>(7, 9, 7979);  

由于5、6、7、9各不相同,所以添加到最终List中为(Item5是Tuple1和Tuple2中Item3之和)

这是我的代码

    for (int a = 0; a < rtSort.Count(); a++) {
            Parallel.For<List<Tuple<int, int, int, int, BigInteger>>>(0, rtSort.Count - 1, () => new List<Tuple<int, int, int, int, BigInteger>>(), (b, loop, storage) => {
                if (rtSort[a].Item1 != rtSort[b].Item1 && rtSort[a].Item1 != rtSort[b].Item2 && rtSort[a].Item2 != rtSort[b].Item2)
                    storage.Add(new Tuple<int, int, int, int, BigInteger>(rtSort[a].Item1, rtSort[a].Item2, rtSort[b].Item1, rtSort[b].Item2, rtSort[a].Item3 + rtSort[b].Item3));
                return storage;
            },
            (x) => {
                lock (rt2) {
                    rt2.AddRange(x);
                }
            });
    }

我已经知道同一个元组中的项目不会相同,所以我只需要检查另一个

rtSort.Count() 的值通常为 500500,这意味着嵌套的Parallel.For 循环和For 循环在完成之前总共进行了 500500*500500 次迭代 (250500250000)。

我的问题是:我可以做些什么来改善这一点和/或我做错了什么,实际上可能会阻碍 Parallel.For 循环的性能

谢谢

【问题讨论】:

  • rt2 的类型是什么?
  • 列表>
  • 如果有 3 个元组的前两个值相同会怎样?
  • 一次不会检查 3 个元组。一次只有 2 个
  • 只是好奇这个问题的上下文。在给出的案例的最坏情况下,可以创建 2500 亿个元组。在处理 50 万个项目时,这似乎有点极端。

标签: c# list for-loop locking parallel.for


【解决方案1】:

如果 AddRange 需要很长时间,如果顺序在结果中不重要,则锁定可能是一个问题

我会对你当前的实现进行基准测试,并使用 ConcurrentBag

   var result =  new ConcurrentBag<Tuple<int, int, int, int, BigInteger>>();

    ...

    (x) => {
        foreach(var item in x)
        {
            result.Add(x);
        }        
    })

【讨论】:

  • 如何将 ConcurrentBag 实现到整个循环中?
  • ConcurrentBag 是一种数据结构,每次添加单个元素都会锁定,不像您的实现会锁定直到添加所有元素
猜你喜欢
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 2011-11-02
  • 1970-01-01
  • 2013-01-29
  • 2016-09-18
  • 2013-02-25
  • 1970-01-01
相关资源
最近更新 更多