gpt4 book ai didi

c++ - 依赖于编译器的OpenMP最小/最大减少编译指示

转载 作者:行者123 更新时间:2023-12-02 10:05:42 25 4
gpt4 key购买 nike

我的C++代码使用OpenMP指令,并且需要与GCC和Visual Studio 2019一起编译。
OpenMP 3.1中引入了OpenMP最小/最大约简运算符,但Visual Studio 2019 only supports OpenMP 2.0

我希望我的代码恢复到Visual Studio下的串行循环,但我理解the preprocessor cannot represent a conditional pragma是这样的:

// invalid use of preprocessor:
#ifdef _MSC_VER
#define OMP_MIN(expr)
#else
#define OMP_MIN(expr) #pragma omp parallel for reduction(min:(expr))
#endif

double x = 10.0;

OMP_MIN(x)
for (int i = 0; i < array_size; i++) {
x = fmin(x, array[i]);
}

有没有办法做到这一点?

最佳答案

您可以使用C++ 11中的_Pragma()来创建类似函数的宏,该宏有条件地启用编译指示:

#include <cmath>

#ifdef _MSC_VER
#define OMP_MINX()
#else
#define OMP_MINX() _Pragma("omp parallel for reduction(min:x)")
#endif

int main() {
double x = 10.0;
double array[50];
int array_size = 50;

OMP_MINX()
for (int i = 0; i < array_size; i++) {
x = std::fmin(x, array[i]);
}
}

但是我还没有弄清楚如何使gcc接受除文字字符串以外的任何参数,以允许使用任意变量-甚至预处理器的字符串化运算符都不起作用,这意味着您也可以使用
#ifndef _MSC_VER
#pragma omp parallel for reduction(min:x)
#endif
for (int i = 0; i < array_size; i++) {
x = std::fmin(x, array[i]);
}

关于c++ - 依赖于编译器的OpenMP最小/最大减少编译指示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60297027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com