reimplement a loop using Parallel.For

85 Views Asked by At

how to re implement the loop below using 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
  }

getting better performance and speed up is the goal.

1

There are 1 best solutions below

3
On

You can mostly just replace the outer loop. However, you need to take care with the setting, as you're setting values from multiple threads:

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]); 
});

However, this may not run any faster, and may actually run significantly slower, as you could easily introduce false sharing since everything is reading from and writing to the same arrays.