Home > Back-end >  Can I conditionally define an openMP parallel region?
Can I conditionally define an openMP parallel region?

Time:04-21

I can write some code that looks like this:

if (make_parallel)
{
    #pragma omp parallel for
    for (int i=0; i<n; i  )
    {
        //For loop stuff
    }
}
else
{
    //Identical for loop, minus the parallelisation
    for (int i=0; i<n; i  )
    {
        //For loop stuff
    }
}

Is there a tidier way of doing this, such that the for loop doesn't have to be duplicated?

[Edit] - So this solution works at the preprocessing level

#define USE_OPENMP

//...

#ifdef USE_OPENMP
#pragma omp parallel for
#endif
for(int i=0;i<n;i  )

But that isn't ideal. But the more I think about it, since defining the parallel region is also preprocessing it probably can't be made conditional in a tidy way?

CodePudding user response:

You can simply use a if clause like this:

int enabled = 1;

#pragma omp parallel if(enabled)
#pragma omp for nowait
for(int i=0;i<n;i  )

Note that this condition could be evaluated by the runtime and not the compiler (GCC does that for example). As a result, the overhead can be significantly higher than your if-else solution for very small loops or the ones in which each iteration is very cheap. The reason is that compilers often do not propagate constants to the OpenMP callback computing function and so the code can make unnecessary operations. This solution has the benefit of being cleaner, helping compilers to produce a smaller binaries and also help to reduce the compilation time (since the loop is compiled once).

  • Related