0

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.

5
  • We don't outright do your work for you here. You need to show us what you've tried already. Commented Dec 22, 2014 at 21:57
  • do a google search and learn how to use Parallel.ForEach Commented Dec 22, 2014 at 21:57
  • How big are your arrays? Do you really need parallelism? (Addition is one of the cheapest instructions) Commented Dec 22, 2014 at 21:59
  • this is not about Parallel.ForEach loop. Commented Dec 23, 2014 at 6:29
  • The data.Length is around one million. Commented Dec 23, 2014 at 6:30

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you; Interlocked.Add Method overloads not support double type, as my arraye named "data" is double. I read related post in this case but this is not clear for me how to exactly rewrite your suggested loop.
This loop is one of my bottleneck in my algorithm as I'm interested to manage it using parallelism to getting speed up. what is any better solution considering False sharing and caching?
@Araz Without interlocked.add, you'd need to do some other form of synchronization (potentially using locking). It might be worth rethinking the algorithm's design to separate out the work so it can be parallelized more easily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.