1

我在尝试学习 RcppParallel 时遇到问题。我尝试修改代码形式https://rcppcore.github.io/RcppParallel/用于向量求和来计算向量的平均值,看看我是否理解一般原理。

我的代码如下所示。在 c(1,2,3,4,5) 上使用函数 parallelVectorMean() 会产生不一致且最常见的错误结果。我认为这与我不了解如何正确访问开始和结束以在加入期间相应地缩放我的部分均值有关。

// [[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;
}

我期待着向你们学习。

4

1 回答 1

1

访问 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;
   }

一个线程可能会在没有加入的情况下继续在新范围上运行,因此您必须考虑这种可能性。

于 2020-11-10T22:01:13.873 回答