Search code examples
c++openmpcpu-cores

How to set the number of CPU cores engaged in a calculation (C++ and OpenMP)


I'm trying to calculate Pi in Qt5 using C++ and OpenMP (with focus on reduction data clause). In this program, I provide the calculation precision and the number of CPU cores engaged.

So far, I have the following code:

    int num_steps= ui->numberStepsLineEdit->text().toInt();
    double x=0.0;
    double sum = 0.0;
    #pragma omp parallel private(i,x)
    {
        #pragma omp for reduction(+:sum) schedule(static)
        for (int i=0; i<num_steps; i++)
        {
             x=(i+0.5)/(double)num_steps;
             sum = sum + 4.0/(1.0+x*x);
        }
     }
     double pi=sum/(double)num_steps;
     QString result= QString::number(pi, 'g', 10);
     ui->piLabel->setText(result);

The problem is that I need to specify the number of CPU cores engaged in the calculation, and I've looked on the internet for examples without success.

How can I set the number of CPU cores engaged in the calculation? (I don't want to set the number of threads).


Solution

  • The way how you can emulate what you're asking for is to set the desired number of cores as the number of threads in the OpenMP code using the num_threads() clause or the omp_set_num_threads() API Call. Then use the OMP_PROC_BIND and OMP_PLACES environment variables to control the mapping of the threads to the number of cores you desire.

    So, for instance, if you would like to use only four cores of the system, you'd do this:

    #pragma omp parallel num_threads(4)
    {
        // your parallel code 
    }
    
    $> OMP_PLACES=cores(4) OMP_PROC_BIND=compact ./a.out