I am trying to understand how the "Parallel.ForEach" function works. I have read the MSDN about it and as an overall understanding it seems that, the more computations you put in the loop the faster it goes in comparison to a normal foreach loop.
Current computer has 4 Cores. (I will have installed my 24 core computer in two days.)
However I think I need some expertise insight in this. I have a sorting algorithm that do a sort in about 10 seconds on 1 core.
I have put a complete code where I do it on one core and where I do it in a: Parallel.ForEach loop with 4 cores.
I simply wonder if it is possible to speed up this sort using more cores in any possible way?
Running testsortFunction() produces below result:
void testsortFunction()
{
String resultstring1 = ""; String resultstring2 = "";
resultstring1 = sortingtestBENCHMARKS(false);
resultstring2 = sortingtestBENCHMARKS(true);
MessageBox.Show(resultstring1 + "\n\n" + resultstring2);
}
String sortingtestBENCHMARKS(bool useParallel)
{
List<String> sortedLIST = new List<String>();
List<String> minusLIST = new List<String>();
List<String> plusLIST = new List<String>();
var stopwatch = new Stopwatch();
//Add 3 million elements
for (double i = 0; i < 1000000; i += 1)
{
plusLIST.Add(i + ",awb/aje" + " - " + "ddfas/asa" + " - " + "asoo/qwa");
}
for (double i = 1; i < 2000000; i += 1)
{
minusLIST.Add("-" + i + ",awb/aje" + " - " + "ddfas/asa" + " - " + "asoo/qwa");
}
//Do the sorting!
if (useParallel == false)
{
stopwatch.Start();
sortedLIST = sortLIST(minusLIST, plusLIST); //11 seconds
stopwatch.Stop();
}
else
{
stopwatch.Start();
Parallel.ForEach("dummy", (c) =>
{
sortedLIST = sortLIST(minusLIST, plusLIST); //32 seconds
});
stopwatch.Stop();
}
return "Elapsed Times in seconds(Using Parallel: " + useParallel + "):\n\n" + stopwatch.Elapsed.TotalSeconds; //10.57 seconds
}
List<String> sortLIST(List<String> minusLIST, List<String> plusLIST)
{
plusLIST = plusLIST.OrderBy(i => double.Parse(i.Split(',')[0])).ToList();plusLIST.Reverse();
minusLIST = minusLIST.OrderBy(i => double.Parse(i.Split(',')[0].TrimStart('-'))).ToList();
plusLIST.AddRange(minusLIST);
return plusLIST;
}

someList.AsParallel().OrderBy(...). Parallel sorting algorithms are very different beasts. If every core tried to access every item all CPU time would be wasted in thrashing and locking. To get any performance boost you need to partition the data and use one task to sort each partition. The sorted partitions have to be merged at the end.Parallel.ForEachis doing much more work.double.Parse(i.Split(',')[0])?? If the text contains European-style decimal separators pass the appropriate CultureInfo object todouble.Parse. Each string operation results in a new temporary string. This means that your code will generate 3 million extra temporary strings