C# 嵌套并行。用于循环性能和大型列表
我正在执行的代码有一个简单的函数。它将一个元组(C# 嵌套并行。用于循环性能和大型列表,c#,list,for-loop,locking,parallel.for,C#,List,For Loop,Locking,Parallel.for,我正在执行的代码有一个简单的函数。它将一个元组(Tuple)的前两项与另一项进行比较,并确定所有项是否不同。如果是,将形成一个组合元组(Tuple),并将其添加到列表中 例如: Tuple<int, int, BigInteger> example1 = new Tuple<int, int BigInteger>(5, 6, 1000); Tuple<int, int, BigInteger> example2 = new Tuple<
Tuple
)的前两项与另一项进行比较,并确定所有项是否不同。如果是,将形成一个组合元组(Tuple
),并将其添加到列表中
例如:
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);
Tuple example1=新的Tuple(5,6,1000);
Tuple example2=新的Tuple(7,9,7979);
由于5、6、7和9都是不同的,它们作为(项5是Tuple1和Tuple2中项3的总和)添加到最终列表中
这是我的密码
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);
}
});
}
for(int a=0;anewlist(),(b,循环,存储)=>{
如果(rtSort[a]。Item1!=rtSort[b]。Item1&&rtSort[a]。Item1!=rtSort[b]。Item2&&rtSort[a]。Item2!=rtSort[b]。Item2)
添加(新元组(rtSort[a].Item1,rtSort[a].Item2,rtSort[b].Item1,rtSort[b].Item2,rtSort[a].Item3+rtSort[b].Item3));
返回存储;
},
(x) =>{
锁(rt2){
rt2.AddRange(x);
}
});
}
我已经知道同一个元组中的项将不相同,所以我只需对照另一个元组进行检查
rtSort.Count()
我的问题是:我能做些什么来改进这一点吗?或者我是否做了一些错误的事情,可能会阻碍并行For循环的性能
谢谢,如果AddRange需要很长时间,如果结果中的顺序不重要,那么锁可能会成为一个问题
我将测试您当前的实现,并使用ConcurrentBag
var result = new ConcurrentBag<Tuple<int, int, int, int, BigInteger>>();
...
(x) => {
foreach(var item in x)
{
result.Add(x);
}
})
var result=new ConcurrentBag();
...
(x) =>{
foreach(x中的变量项)
{
结果:添加(x);
}
})
rt2的类型是什么?列表如果有3个元组的前两个值相同会发生什么情况?一次不会检查3个元组。一次只有两个人,只是好奇这个问题的背景。在本案例的最坏情况下,可能会创建2500亿个元组。在处理500K项时,这似乎有点极端。我如何在整个循环中实现ConcurrentBag?ConcurrentBag是一种数据结构,每次添加单个元素时都会锁定,而您的实现在添加所有元素之前都会锁定