user1019083
user1019083

Reputation: 381

how parallelize this function

I have a function which is quite time consuming and it goes like this since the value of n is very large

sum=0; for(i=0;i<n;i++)
{
     a=func(i,b);
     c=func(i,a);
     sum+=c;  
}

Is it possible to parallelize this loop using openMp?

Upvotes: 1

Views: 249

Answers (1)

Mysticial
Mysticial

Reputation: 471379

Here's the short way:

int sum = 0;

#pragma omp parallel for reduction(+:sum)
    for(i = 0; i < n; i++){
        int a = func(i,b);
        int c = func(i,a);
        sum += c;
    }

Here's a longer (but more flexible) way:

int sum = 0;

#pragma omp parallel
    {
        int local_sum = 0;

#pragma omp for
        for(i = 0; i < n; i++){
            a = func(i,b);
            c = func(i,a);
            local_sum += c;
        }

#pragma omp critical
        {
            sum += local_sum;
        }
    }

Upvotes: 4

Related Questions