*Please note that I am just testing to understand this.
I am trying to use all the cores of my computer with the Parallel.For()
method. This is working just fine, but when I am trying the same method with a normal for loop it is going much faster. The parallel method is taking 16 sec and the normal method is only taking 6 sec.
I hope you can tell me what I am doing wrong here.
DateTime parallelStart = new DateTime();
DateTime parallelFinish = new DateTime();
DateTime singeStart = new DateTime();
DateTime singeFinish = new DateTime();
parallelStart = DateTime.Now;
int inputData = 0;
Parallel.For(0, 1000000000, i =>
{
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
});
parallelFinish = DateTime.Now;
singeStart = DateTime.Now;
for (int i = 0; i < 1000000000; i++)
{
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
inputData = inputData++;
}
singeFinish = DateTime.Now;
MessageBox.Show("Parallel execution time: " + (parallelFinish - parallelStart).Seconds + "\n" +
"Singe execution time: " + (singeFinish - singeStart).Seconds);
DateTime parallelStart = new DateTime();
DateTime parallelFinish = new DateTime();
DateTime singeStart = new DateTime();
DateTime singeFinish = new DateTime();
parallelStart = DateTime.Now;
Parallel.For(0, 2000000000, i =>
{
var inputData = 0;
});
parallelFinish = DateTime.Now;
singeStart = DateTime.Now;
for (int i = 0; i < 2000000000; i++)
{
var inputData = 0;
}
singeFinish = DateTime.Now;
MessageBox.Show("Parallel execution time: " + (parallelFinish - parallelStart).Seconds + "\n" + "Singe execution time: " + (singeFinish - singeStart).Seconds);
Well, what's faster: doing no work yourself, or hiring ten guys to each do one tenth of no work?
What you're doing wrong is that your example is completely artificial. The jitter is fully aware that assigning zero to the same local that is unused over and over again is pointless, so it is probably eliminating the work. Even if it is not, that work is trivial. The work of setting up all the threads is larger than just doing the work yourself.
Do a real test -- do some raytracing or generate a fractal or something in there. Do something realistic that will take minutes or hours on one thread. You cannot reasonably expect to see a savings on a job that is too easy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With