So I am currently working on a project and now I feel the need to try and speed up the execution. I have a method with a foreach loop in it that I wish to parallelize as efficiently as possible.
This is how it looks now:
public void Simulate()
{
List
int min = int.MaxValue;
int bestX = -1, bestY = -1;
foreach (Coordinate currPos in Locations)
{
string[,] tempMap = new string[globalMap.GetLength(0), globalMap.GetLength(1)];
matrixCopy(globalMap, tempMap);
int result = processData(currPos, tempMap);
if (result < min)
{
min = result;
bestX = currPos.X;
bestY = currPos.Y;
}
}
MessageBox.Show(bestX + " " + bestY + " " + min);
}
I would like to change the foreach loop to use Parallel.ForEach or perhaps use PLINQ. My concerns are how I can find the minimal value with as little locking as possible. Also I want to preserve some other values than just the minimum.
Another issue is the globalMap, is it good to copy it like I do now? All threads can't work on the original at the same time because they change the data. But perhaps I should do the copy in my processData()-method? Any thoughts?
VulpesPosted Oct 11, 2011, 7:04 AM
VulpesPosted Oct 13, 2011, 5:02 AM
Shand RamziPosted Oct 13, 2011, 1:19 AM
But can't you change these two lines
min = bag.AsParallel().Min(t => t.Item2);
Tuple
To only be one statement? Can't I have
min = bag.AsParallel().Min(t => t.Item2);
return a tuple right away?
I mean it feels like I should be able to do it with one statement instead of in practice looping through the bag twice. Can't I traverse the bag looking for the min value of Item2 and have it return the full tuple right away instead of only the int part?
VulpesPosted Oct 12, 2011, 6:11 AM
You could also do it by sorting though I think that would definitely be slower:
Notice that if there were more than one minimum result, then these approaches might not necessarily return the same Coordinate object as the foreach loop.
Shand RamziPosted Oct 12, 2011, 5:07 AM
I'm currently trying to learn (P)LINQ also. Would there be a way to go through the bag and find the minimum object (according to some criteria) with (P)LINQ? I mean replacing the final foreach with a (P)LINQ statement.
Could be good to learn.