I am trying to write a simple application using OpenMP. Unfortunately, I have problems with acceleration. In this application, I have one while loop. The body of this cycle consists of some instructions that must be executed sequentially and one for the cycle. I use #pragma omp parallel forto make this for the loop parallel. This cycle does not have much work, but it is called very often.
I am preparing two versions of the for loop and running the application on 1, 2 and 4cores.
version 1 (4 iterations in a loop): 22 sec, 23 s, 26 sec.
version 2 (100,000 iterations in a loop): 20 s, 10 s, 6 sec.
As you can see, when there is not much work for the cycle, the time on 2 and 4 cores is higher than on 1core. I think the reason is because it #pragma omp parallel forcreates new threads in each iteration of the while loop. So, I would like to ask you - is it possible to create threads once (before the while loop) and guarantee that some execution of the while loop will be executed sequentially?
#include <omp.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(int argc, char* argv[])
{
double sum = 0;
while (true)
{
#pragma omp parallel for num_threads(atoi(argv[1])) reduction(+:sum)
for(int j=0; j<4; ++j)
{
double x = pow(j, 3.0);
x = sqrt(x);
x = sin(x);
x = cos(x);
x = tan(x);
sum += x;
double y = pow(j, 3.0);
y = sqrt(y);
y = sin(y);
y = cos(y);
y = tan(y);
sum += y;
double z = pow(j, 3.0);
z = sqrt(z);
z = sin(z);
z = cos(z);
z = tan(z);
sum += z;
}
if (sum > 100000000)
{
break;
}
}
return 0;
}
source
share