如何使用Parallel.For?
重新实现下面的循环for (int i = 0; i < data.Length; ++i)
{
int cluster = clustering[i];
for (int j = 0; j < data[i].Length; ++j)
means[cluster][j] += data[i][j]; // accumulate sum
}
获得更好的性能和加速是我们的目标。
答案 0 :(得分:3)
你几乎可以只更换外环。但是,您需要注意设置,因为您要从多个线程设置值:
Parallel.For(0, data.Length, i =>
{
int cluster = clustering[i];
for (int j = 0; j < data[i].Length; ++j)
Interlocked.Add(ref means[cluster][j], data[i][j]);
});
然而,这可能不会运行得更快,并且可能实际上运行速度明显变慢,因为您可以轻松地引入false sharing,因为所有内容都在读取和写入相同的数组。