Openmp和std :: vector上的还原? [英] Openmp and reduction on std::vector?
问题描述
我想使这段代码平行:
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];
}
在此文章中,建议使用:
#pragma omp parallel for reduction(+:myArray[:6])
在这个问题中,在评论部分提出了相同的方法.
In this question the same approach is proposed in the comments section.
我有两个问题:
- 在编译时我不知道
m
,从这两个示例看来,这是必需的.是这样吗?或者,如果我可以在这种情况下使用它,那么我必须在以下命令#pragma omp parallel for reduction(+:res[:?])
中将?
替换为什么?m
或n
? -
for
的索引相对于indexes
和vals
而不是相对于res
是否有意义,尤其是考虑到reduction
是在后者上完成的?
- I don't know
m
at compile time, and from these two examples it seems that's required. Is it so? Or if I can use it for this case, what do I have to replace?
with in the following command#pragma omp parallel for reduction(+:res[:?])
?m
orn
? - Is it relevant that the indexes of the
for
are relative toindexes
andvals
and not tores
, especially considering thatreduction
is done on the latter one?
但是,如果可以,我该如何解决这个问题?
However, If so, how can I solve this problem?
推荐答案
为用户声明的特定类型C ++向量的归约化是相当简单的:
It is fairly straight forward to do a user declared reduction for C++ vectors of a specific type:
#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[...] += ...;
}
1a)不需要在编译时不知道m
.
1a) Not knowing m
at compile time is not a requirement.
1b)您不能在std::vector
上使用数组节缩减,因为它们不是数组(并且std::vector::data
不是标识符).如果可能的话,您必须使用n
,因为这是数组部分中的元素数.
1b) You cannot use the array section reduction on std::vector
s, because they are not arrays (and std::vector::data
is not an identifier). If it were possible, you'd have to use n
, as this is the number of elements in the array section.
2)只要您只阅读indexes
和vals
,就没有问题.
2) As long as you are only reading indexes
and vals
, there is no issue.
原始的initializer
原因更简单:initializer(omp_priv = omp_orig)
.但是,如果原始副本没有满零,那么结果将是错误的.因此,我建议使用更复杂的初始化程序,该初始化程序始终创建零元素向量.
The original initializer
caluse was simpler: initializer(omp_priv = omp_orig)
. However, if the original copy is then not full of zeroes, the result will be wrong. Therefore, I suggest the more complicated initializer which always creates zero-element vectors.
这篇关于Openmp和std :: vector上的还原?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!