I'm using Parallel.For
to improve the performance of some long running code, which I've simplified here.
Increasing the MaxDegreeOfParallelism
from 1 to 2 cuts the time to complete to about half, but increasing from 2 to 3 cuts the time by only a quarter. Any subsequent increases improves the performance even less. However, the CPU % seen in Task Manager keeps increasing linearly, which means that the CPU is working harder and harder for less performance gains the higher the MaxDegreeOfParallelism
is.
How is that possible? What is the CPU spending the cycles on? Can anything be done with the code improve performance at higher parallel degrees?
using System.Diagnostics;
float sum = 0f;
Stopwatch sw = Stopwatch.StartNew();
Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = -1 }, (iter) =>
{
float answer = 0f;
for (int i = 0; i < 100000; i++)
{
for (int j = 0; j < 100; j++)
answer += MathF.Sqrt(i * j);
}
sum += answer;
});
Console.WriteLine($"{sw.ElapsedMilliseconds} {sum}");
The below tests were done in Release mode, on a quad core CPU with 8 logical cores.