使用与 openmp C++并行的循环计算矩阵中每一行的最小值



我想使用 openmp c++ 并行计算矩阵中每一行的最小值,如下所示:

// matrix Distf (float) of size n by n is declared before. 
vector<float> minRows;
#pragma omp parallel for
for (i=0; i < n; ++i){
float minValue = Distf[i][0];
#pragma omp parallel for reduction(min : minValue)
for (j=1; j < n; ++j){
if (Distf[i][j] < minValue){
minValue = Distf[i][j];
}
}
minRows.push_back(minValue);
}

到目前为止,编译器没有引发任何错误,但我想知道这是否会像预期的那样给出正确的答案?谢谢

我们在评论中谈到的答案: 由于无论如何我都必须编写一些样板,因此我使用 ints 作为类型,并且完全避免考虑浮点问题:

#include <vector>
#include <iostream>
using namespace std;
int main(){
constexpr size_t n = 3;
// dummy Distf (int) declared in lieu of matrix Distf 
int Distf[n][n] = {{1,2,3},{6,5,4},{7,8,8}};
//could be an array<int,n> instead
vector<int> minRows(n);
#pragma omp parallel for
for (size_t i = 0; i < n; ++i){
int minValue = Distf[i][0];
// Alain Merigot argues this is a performance drag
//#pragma omp parallel for reduction(min : minValue)
for (size_t j = 1; j < n; ++j){
if (Distf[i][j] < minValue){
minValue = Distf[i][j];
}
}
//minRows.push_back(minValue) is a race condition!
minRows[i] = minValue;
}
int k = 0;
for(auto el: minRows){
cout << "row " << k++ << ": " << el << 'n';
}
cout << 'n';
}

内部循环通常不需要并行化。我不知道你可以使用多少个内核,但除非你在一个大规模并行系统上,想想GPU级别的并行性,外循环应该已经利用了所有可用的内核,或者问题只是不够大。在任何一种情况下启动更多线程都是一种悲观。

最新更新