Search code examples
c++c++11openmp

How to override the OpenMp runtime scheduling policy using OMP_SCHEDULE environment variable?


I have an openMP parallel for loop of the form

#pragma omp for schedule(dynamic)
for(std::size_t i = 0 ; i < myArray.size() ; i++)
{
  //some code here
}

In other words by default this loop uses dynamic scheduling. However if the user specifies the OMP_SCHEDULE environment variable I want to be able to override the dynamic policy with whatever policy is specified in OMP_SCHEDULE. How can this be done? In other words if OMP_SCHEDULE is not specified I want to use a dynamic schedule by default. It is my understanding that in the above code, because I have specified schedule(dynamic) it is going to ignore any policy specified in OMP_SCHEDULE, is this correct? Thanks


Solution

  • To get what you want, you'll probably need to do a bit of manual intervention. During initialization, I'd add some code on this general order:

    #include <omp.h>
    
    std::string scheduling = getenv("OMP_SCHEDULE");
    
    // If the user didn't specify anything, set the default we want.
    if (scheduling.empty()) 
       omp_set_schedule(omp_sched_dynamic, -1);
    

    Then for your loop, specify schedule(runtime) scheduling strategy in the #pragma, so it'll use what was set by OMP_SCHEDULE environment variable, or by us above:

    #pragma omp for schedule(runtime)
    for(std::size_t i = 0 ; i < myArray.size() ; i++)
    {
      //some code here
    }
    

    Passing -1 for the chunk size tells the runtime to select its default. Depending on the situation, explicitly setting a different value may improve performance (but -1 should be equivalent to not specifying the chunk size, as you did in your #pragma).