我正在寻找在代码中使用OMP_PLACES
和OMP_PROC_BIND=close
的正确方法。当我运行这个时,我得到的是:
error: ‘OMP_PLACES’ was not declared in this scope
#include <iostream>
#include <random>
#include <fstream>
#include <iomanip>
#include <cfloat>
#include <omp.h>
#include <stdlib.h>
using namespace std;
int main()
{
const int N = 100;
unsigned seed = 0;
double sum = 0.0;
double avg;
srand(seed);
default_random_engine g(seed);
uniform_real_distribution<double> distribution(0.0f, nextafter(1.0f, DBL_MAX));
#pragma omp parallel
{
OMP_PLACES="cores(4)";
OMP_PROC_BIND=close;
#pragma omp for reduction (+: sum)
for (int i = 0; i < N; i++) {
double x = distribution(g);
sum = sum + x;
}
avg = sum / static_cast<double> (N);
}
}
必须在shell环境中设置OMP_PLACES
和OMP_PROC_BIND
变量。所以,如果你使用bash,那么你可以这样做:
$ export OMP_PLACES="cores(4)"
$ export OMP_PROC_BIND=close
$ ./your_application
另一种选择是在代码中使用proc_bind()
子句:
// header omitted
int main()
{
const int N = 100;
unsigned seed = 0;
double sum = 0.0;
double avg;
srand(seed);
default_random_engine g(seed);
uniform_real_distribution<double> distribution(0.0f, nextafter(1.0f, DBL_MAX));
#pragma omp parallel proc_bind(close)
{
#pragma omp for reduction (+: sum)
for (int i = 0; i < N; i++) {
double x = distribution(g);
sum = sum + x;
}
// remainder of code to follow
}
...
}
然后你仍然需要
$ export OMP_PLACES="cores(4)"
指定您希望代码运行的位置。
PS:你可能还想查看这个关于随机数生成器的C++线程安全的SO页面:随机数生成器的C++11线程安全