Parallel.ForEach<int, long>(lista, () => 0, (j, loop, subsum) =>
{
if (subsum > 20000)
{
loop.Break();
}
subsum += lista[j];
return subsum;
}, (x) => Interlocked.Add(ref sum, x));
• Parallel.For 和for 性能测试比较 我们这里产生1千万个随机数为例子做个一个性能比较,在笔者的笔记本上结果如下 (可能在你的电脑上得到结果不一定相同)
附上相关的代码给大家参考
复制代码 代码如下:
int listLength = 10000000;
List<int> listTask = new List<int>();
List<int> list = new List<int>();
Stopwatch watch1 = Stopwatch.StartNew();
Parallel.For(0, listLength, i => {
Random r = new Random(100);
listTask.Add(r.Next());
});
Console.WriteLine("并行耗时:" + watch1.ElapsedMilliseconds );
Stopwatch watch2 = Stopwatch.StartNew();
for (int i = 0; i < listLength; i++)
{
Random r = new Random(100);
list.Add(r.Next());
}
Console.WriteLine("非并行耗时:" + watch2.ElapsedMilliseconds );
您可能感兴趣的文章: