使用与 openmp C++并行的循环计算矩阵中每一行的最小值
Compute the minimum value of every row in a matrix using loops parallel with 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级别的并行性,外循环应该已经利用了所有可用的内核,或者问题只是不够大。在任何一种情况下启动更多线程都是一种悲观。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用递归的数组的最小值.这是怎么回事
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- txt 文件中浮点数的最大和最小值
- 余数运算符的等效操作,用于处理低于允许的最小值
- 需要使用模板查找数组的第二个最小和最小值
- CUDA - 将 float3 数组的 (x,y,z) 分量的最小值/最大值分开?
- 查找包含 N 个元素的数组的最小值和最大值
- 错误C++在Visual Studio 2019中使用numeric_limits的长双精度最小值/最大值
- 是否存在用于 C 或 C++ 中常见数学运算(例如最小值、最大值和平均值)的可导入库?
- 如何在 c++ 中创建对的优先级队列.这会弹出具有最小值的元素.默认的弹出最大值
- 将最小值整数转换为无符号长整型
- 使用与 openmp C++并行的循环计算矩阵中每一行的最小值
- C++在二维数组中的每一行和每一列中查找最小值和最大值
- 求n*m矩阵每一行的最小值