Sunday, May 31, 2009

I would like to close this month with the comparison of Parallel.For and serial for loop. For comparison, I took an INEFFICIENT algorithm to find if a given number is prime. Here is the algorithm:


Here is the serial for loop to find the primes from 2 to 100000:

And here is its output:


Note down the Thread ID, and it took 24511 milliseconds. And here is its equivalent Parallel code:



Here comes the output:

Did you notice that 6 different threads run the code in parallel and it took 18220 milliseconds? The Parallel class uses Task class behind the scenes, to parallelize the loop iterations. And depending upon the number of cores of your CPU, it determines the optimal number of threads and assigns these tasks to the threads.

This program determines prime number in a big range of 100000 numbers. But if you replace the both programs for less numbers, say 5000, or 10000, then the serial for loop will be more efficient. Because, Task objects creation incurs overhead and exceeds the solution time. So, if your problem is small try to avoid parallelize your code.

No comments:

Post a Comment