首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RcppParallel RVector push_back还是类似的东西?

RcppParallel RVector push_back还是类似的东西?
EN

Stack Overflow用户
提问于 2018-03-13 17:12:57
回答 1查看 320关注 0票数 1

我正在使用RcppParallel加速一些计算。但是,我在这个过程中内存不足,所以我想在并行循环中保存通过一些相关阈值的结果。下面是一个玩具例子来说明我的观点:

代码语言:javascript
复制
#include <Rcpp.h>
#include <RcppParallel.h>
using namespace Rcpp;

// [[Rcpp::depends(RcppParallel)]]
// [[Rcpp::plugins(cpp11)]]
struct Example : public RcppParallel::Worker {
  RcppParallel::RVector<double> xvals, xvals_output, yvals;
  Example(const NumericVector & xvals, NumericVector & yvals, NumericVector & xvals_output) : 
    xvals(xvals), xvals_output(xvals_output), yvals(yvals) {}
  void operator()(std::size_t begin, size_t end) {
    for(std::size_t i=begin; i < end; i++) {
      double y = xvals[i] * (xvals[i] - 1);
      // if(y < 0) {
      //   xvals_output.push_back(xvals[i]);
      //   yvals.push_back(y);
      // }
      xvals_output[i] = xvals[i];
      yvals[i] = y;
    }
  }
};
// [[Rcpp::export]]
List find_values(NumericVector xvals) {
  NumericVector xvals_output(xvals.size());
  NumericVector yvals(xvals.size());
  Example ex(xvals, yvals, xvals_output);
  parallelFor(0, xvals.size(), ex);
  List L = List::create(xvals_output, yvals);
  return(L);
}

R代码将是:

代码语言:javascript
复制
find_values(seq(-10,10, by=0.5))

注释掉的代码是我想要做的。

也就是说,我想初始化一个空向量,并且只附加通过某个阈值的y-值以及相关的x-值。

在我的实际用法中,我正在计算一个MxN矩阵,所以内存是一个问题。

处理这个问题的正确方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-14 18:49:17

如果有人遇到类似的问题,这里有一个使用TBB中的"concurrent_vector“的解决方案( RcppParallel在幕后使用,并且可以作为标题使用)。

代码语言:javascript
复制
#include <Rcpp.h>
#include <RcppParallel.h>
#include <tbb/concurrent_vector.h>
using namespace Rcpp;

// [[Rcpp::depends(RcppParallel)]]
// [[Rcpp::plugins(cpp11)]]
struct Example : public RcppParallel::Worker {
  RcppParallel::RVector<double> xvals;
  tbb::concurrent_vector< std::pair<double, double> > &output;
  Example(const NumericVector & xvals, tbb::concurrent_vector< std::pair<double, double> > &output) : 
    xvals(xvals), output(output) {}
  void operator()(std::size_t begin, size_t end) {
    for(std::size_t i=begin; i < end; i++) {
      double y = xvals[i] * (xvals[i] - 1);
      if(y < 0) {
        output.push_back( std::pair<double, double>(xvals[i], y) );
      }
    }
  }
};
// [[Rcpp::export]]
List find_values(NumericVector xvals) {
  tbb::concurrent_vector< std::pair<double, double> > output;
  Example ex(xvals,output);
  parallelFor(0, xvals.size(), ex);
  NumericVector xout(output.size());
  NumericVector yout(output.size());
  for(int i=0; i<output.size(); i++) {
    xout[i] = output[i].first;
    yout[i] = output[i].second;
  }
  List L = List::create(xout, yout);
  return(L);
}

输出:

代码语言:javascript
复制
> find_values(seq(-10,10, by=0.5))
[[1]]
[1] 0.5

[[2]]
[1] -0.25
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49262061

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档