0

VC++, testing OpenMP parallelism for nested loops, but it gives strange results:

  • No performance increase
  • For big loops SUM calculation is wrong. if it is only 5 nested loops, then it is ok.

Here is the result:

Sum=450000000000.000000 Serial time:        117376.852855
Sum=228067994200.000000 Parallel time:      117391.867931

Here is the working code:

#include "stdafx.h"
#include <omp.h>
#include <ppl.h>

double Serial(), Parallel();

int _tmain(int argc, _TCHAR* argv[])
{
printf("Sum=%f Serial time:        %lf\n",Serial(),omp_get_wtime() );
printf("Sum=%f Parallel time:      %lf\n",Parallel(),omp_get_wtime() );

return 0;
}

double Serial()
{
double sum=0.;
int n=10;

for (int i01=0; i01<n; i01++){
for (int i02=0; i02<n; i02++){
for (int i03=0; i03<n; i03++){
for (int i04=0; i04<n; i04++){
for (int i05=0; i05<n; i05++){
for (int i06=0; i06<n; i06++){
for (int i07=0; i07<n; i07++){
for (int i08=0; i08<n; i08++){
for (int i09=0; i09<n; i09++){
for (int i10=0; i10<n; i10++){

sum+=i01+i02+i03+i04+i05+i06+i07+i08+i09+i10;

}}}}} }}}}}
return sum;
}

double Parallel()
{
double sum=0.;

#pragma omp parallel for shared(sum)
for (int i01=0; i01<10; i01++){
for (int i02=0; i02<10; i02++){
for (int i03=0; i03<10; i03++){
for (int i04=0; i04<10; i04++){
for (int i05=0; i05<10; i05++){
for (int i06=0; i06<10; i06++){
for (int i07=0; i07<10; i07++){
for (int i08=0; i08<10; i08++){
for (int i09=0; i09<10; i09++){
for (int i10=0; i10<10; i10++){

sum+=i01+i02+i03+i04+i05+i06+i07+i08+i09+i10;

}}}}} }}}}}
return sum;
}

1 Answer 1

0

You have correctly guessed that sum should be shared, but in fact it is a reduction variable and has to be put in a reduction clause instead:

#pragma omp parallel for reduction(+:sum)

Another option (slower) would be make the increment atomic. Atomic operations would be an overkill in this case, but they help in more complex cases, when simple reductions are not applicable, for example when reducing over arrays:

#pragma omp atomic update
sum+=i01+i02+i03+i04+i05+i06+i07+i08+i09+i10;

The update clause comes from OpenMP 3.1. Visual Studio supports only 2.0 so it would not understand it, but you never know - you might want to move to a better compiler some day.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.