我在尝试学习RcppParallel时遇到了一个问题。我试着修改了向量求和的代码形式https://rcppcore.github.io/RcppParallel/,改为计算向量的平均值,看看我是否理解了一般原理。
我的代码如下所示。在c(1,2,3,4,5)上使用函数parallelVectorMean()会产生不一致的结果,而且通常是不正确的结果。我认为这与我不理解如何正确地访问begin和end来在连接期间相应地缩放我的部分方法有关。
// [[Rcpp::depends(RcppParallel)]]
#include <RcppParallel.h>
#include <Rcpp.h>
using namespace RcppParallel;
struct Mean : public Worker
{
// source vector
const RVector<double> input;
// accumulated value
double value;
// number of elements
double num;
// constructors
Mean(const Rcpp::NumericVector input) : input(input), value(0), num(0) {}
Mean(const Mean& mean, Split) : input(mean.input), value(0), num(0) {}
// accumulate just the element of the range I've been asked to
void operator()(std::size_t begin, std::size_t end) {
num = (double) end - (double) begin;
value += (std::accumulate(input.begin() + begin, input.begin() + end, 0.0) / num);
}
// join my value with that of another Mean
void join(const Mean& rhs) {
value = (num*value + rhs.num*rhs.value)/(num + rhs.num);
num = num + rhs.num;
}
};
// [[Rcpp::export]]
double parallelVectorMean(Rcpp::NumericVector x) {
// declare the MeanBody instance
Mean mean(x);
// call parallel_reduce to start the work
RcppParallel::parallelReduce(0, x.length(), mean);
// return the computed mean
return mean.value;
}我期待着向你们学习。
发布于 2020-11-11 06:01:14
访问begin和end没有问题,但是运算符函数的逻辑不正确。
检查以下内容:
void operator()(std::size_t begin, std::size_t end) {
double temp_num = (double) end - (double) begin;
double temp_value = (std::accumulate(input.begin() + begin, input.begin() + end, 0.0) / temp_num);
value = (num*value + temp_num*temp_value)/(num + temp_num);
num = num + temp_num;
}线程可能会继续在新的范围内运行,而不会加入,因此您必须考虑到这种可能性。
https://stackoverflow.com/questions/64759518
复制相似问题