【发布时间】:2015-07-25 00:56:46
【问题描述】:
我正在尝试在 OpenMP 中使用 malloc 分配的大型数组来实现 dotproduct。但是,当我使用 reduction(+:result) 时,它会为每个程序运行产生不同的结果。为什么我会得到不同的结果?我该如何补救?以及如何优化这个例子?这是我的代码:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <omp.h>
const int N = 1e1;
int main ()
{
int i, nthreads, tid;
double x_seq, x_par, *y, *z, cpu_time_used;
clock_t start, end;
y = (double*)malloc(sizeof(double)*N);
z = (double*)malloc(sizeof(double)*N);
for (i=0; i<N; i++) {
y[i] = i * 1.0;
z[i] = i * 2.0;
}
x_seq = 0;
x_par = 0;
for (i=0; i<N; i++) x_seq += y[i] * z[i];
#pragma omp parallel shared(y, z) private(i, tid)
{
#pragma omp single
{
nthreads = omp_get_num_threads();
}
tid = omp_get_thread_num();
#pragma omp parallel for reduction(+:x_par)
for (i=tid; i<N; i+=nthreads)
{
x_par += y[i] * z[i];
}
}
return 0;
}
【问题讨论】:
-
请用您使用的编程语言标记您的问题。 (我假设这是 C?)另外,请注意,如果这是 C(不是 C++),那么 don't cast the return value of
malloc(). -
回答你的问题
how can this example be optimized?答案是it's memory bandwidth bound so it won't scale with the number of threads though that does not mean multiple threads won't help。 -
@ace,这是有效的 C/C++ 代码,但不强制转换会使 C++ 代码无效。关于这个问题,你有什么有用的要说的吗?
-
@Zboson 检查修订历史。第一个版本没有标记语言,所以我要求 OP 相应地标记它。而且由于我注意到 OP 使用的是
<stdlib.h>而不是<cstdlib>,所以我猜它是 C 而不是 C++,所以我补充说,如果这是 C,它不应该被强制转换。如果你仍然认为我做了什么,请解释更多错了。此外,现在它被标记为 C,它使我之前的评论更加有用。 -
@ace 投不投是见仁见智的事,没有对错之分。
标签: c pointers for-loop openmp reduction