我希望在 for 循环中找到计算值的最大值,并存储其对应的索引 max_calc_value 和 i_max 这里,下面是我的伪代码。我想知道是否可以在这里进行某种减少:
double max_calc_value = -DBL_MAX; // minimum double value
#pragma omp parallel for
for (int i = 20; i < 1000; i++) {
this_value = my_slow_function(large_double_vector_array, param1*i, .., param5+i);
if (this_value > max_calc_value){
max_calc_value = this_value;
i_max = i;
}
}
最佳答案
如果你愿意,你可以定义一个自定义的缩减函数并并行使用它。在您的特定示例中,这可能只会使代码比简单地使用 critical
部分更麻烦。但是,如果您的实际代码可以从使用此自定义缩减功能中全局受益,这可能会很好地应用,不仅适用于最终的并行缩减,还适用于本地代码......
因此,如果它适用于你,这里有一个关于它如何工作的例子:
#include <iostream>
#include <omp.h>
struct dbl_int {
double val;
int idx;
};
const dbl_int& max( const dbl_int& a, const dbl_int& b) {
return a.val > b.val ? a : b;
}
#pragma omp declare reduction( maxVal: dbl_int: omp_out=max( omp_out, omp_in ) )
int main() {
dbl_int di = { -100., -1 };
#pragma omp parallel num_threads( 10 ) reduction( maxVal: di )
{
di.val = omp_get_thread_num() % 7;
di.idx = omp_get_thread_num();
}
std::cout << "Upon exit, value=" << di.val << " and index=" << di.idx << std::endl;
return 0;
}
这给了我:
~/tmp $ g++ -fopenmp myred.cc -o myred
~/tmp $ ./myred
Upon exit, value=6 and index=6
关于c++ - 在 C++11 中使用 OpenMP 查找计算值的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39989473/