我有这个 C++ 代码。
循环遍历矩阵,找到每行中的最小元素,并从相应行的每个元素中减去它。 变量 myr 是所有 min 元素的总和
尝试并行:
int min = 0;
int myr = 0;
int temp[SIZE][SIZE];
int size = 0;
...//some initialization
omp_set_num_threads(1);
start_time = omp_get_wtime();
#ifdef _OPENMP
#pragma omp parallel for firstprivate(min, size) reduction(+:myr)
#endif
for(int i = 0; i < size; i++){
min = INFINITY;
for(int j = 0; j < size; j++){
if (temp[i][j] < min)
min = temp[i][j];
}
myr+=min;
for(int j = 0; j < size; j++)
temp[i][j]-=min;
}
end_time = omp_get_wtime();
如果我设置 omp_set_num_threads(2);
这部分代码开始运行得更慢。
我的proc有2个核心
为什么使用 2 个线程时代码运行速度较慢?
最佳答案
一定有一些别名或其他事情发生了。让 OpenMP 更简单:
int const size0 = size;
#ifdef _OPENMP
#pragma omp parallel for reduction(+:myr)
#endif
for(int i = 0; i < size0; i++){
int min = INFINITY;
int * tmp = temp[i];
for(int j = 0; j < size0; j++){
if (tmp[j] < min)
min = tmp[j];
}
for(int j = 0; j < size0; j++)
tmp[j]-=min;
myr+=min;
}
也就是说,如果可能的话,将大部分变量设为本地变量和 const
。
关于c++ - openmp:增加线程数会降低性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12352532/