-1

我正在执行的代码有一个简单的功能。它将元组 ( 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中为<5、6、7、9、1000+7979>(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 循环的性能

谢谢

4

1 回答 1

0

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

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

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

    ...

    (x) => {
        foreach(var item in x)
        {
            result.Add(x);
        }        
    })
于 2016-10-12T22:36:41.210 回答