Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide FOR loop in N even parts for parallel execution given constant input data for each iteration?

I have a time consuming loop I would like to execute in parallel. Pseudocode:

for(int n = 0; n < 2048; n++)
{
  output_data[n] = function(constant_input_data, n)
}
  • Input data for each iteration is completely the same
  • Output for Nth iteration is stored in array with index N.

How to divide this loop in C equal parts, where C is CPU core count?

What is the best and the most elegant way to do this in C#, .net?

like image 851
JBeurer Avatar asked Jan 30 '12 06:01

JBeurer


1 Answers

Using Parallel.For of TPL

Parallel.For( 0, 2048, n=>
   {
         output_data[n] = function(constant_input_data, n);
    });

TPL tries to spawn as many threads as the no. of cpu cores you have and then your work is divided in tasks that are scheduled on those threads. So it is 2048 tasks on possibly x no. of threads where x is no. of cores.

like image 91
Muhammad Hasan Khan Avatar answered Sep 28 '22 16:09

Muhammad Hasan Khan