jus*_*rld 5 c++ parallel-processing vector openmp reduction
我想让这段代码并行:
std::vector<float> res(n,0);
std::vector<float> vals(m);
std::vector<float> indexes(m);
// fill indexes with values in range [0,n)
// fill vals and indexes
for(size_t i=0; i<m; i++){
res[indexes[i]] += //something using vas[i];
}
Run Code Online (Sandbox Code Playgroud)
在这个文章它的建议使用:
#pragma omp parallel for reduction(+:myArray[:6])
Run Code Online (Sandbox Code Playgroud)
在这个问题中,评论部分提出了相同的方法.
我有两个问题:
m在编译时,从这两个例子看来,它似乎是必需的.是这样吗?或者,如果我可以在这种情况下使用它,我需要?在以下命令中替换#pragma omp parallel for reduction(+:res[:?])什么?m还是n?for是相对于indexes和vals,而不是res,尤其是考虑到reduction是在后者做了什么?但是,如果是这样,我该如何解决这个问题呢?
为特定类型的C++向量执行用户声明的减少是相当直接的:
#include <algorithm>
#include <vector>
#pragma omp declare reduction(vec_float_plus : std::vector<float> : \
std::transform(omp_out.begin(), omp_out.end(), omp_in.begin(), omp_out.begin(), std::plus<float>())) \
initializer(omp_priv = decltype(omp_orig)(omp_orig.size()))
std::vector<float> res(n,0);
#pragma omp parallel for reduction(vec_float_plus : res)
for(size_t i=0; i<m; i++){
res[...] += ...;
}
Run Code Online (Sandbox Code Playgroud)
1a)m不需要在编译时知道.
1b)你不能在std::vectors 上使用数组部分缩减,因为它们不是数组(并且std::vector::data不是标识符).如果可能的话,你必须使用n,因为这是数组部分中的元素数量.
2)只要你只是读取indexes和vals,也没有问题.