Skip to content

Instantly share code, notes, and snippets.

@YulongNiu
Last active July 23, 2018 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YulongNiu/add0d9f066299613b64b8458fd5d741a to your computer and use it in GitHub Desktop.
Save YulongNiu/add0d9f066299613b64b8458fd5d741a to your computer and use it in GitHub Desktop.
Test Rcpp parallel with C++ versions
#include <RcppArmadillo.h>
#include <RcppParallel.h>
#include <algorithm>
#include <cmath>
using namespace Rcpp;
using namespace RcppParallel;
using namespace arma;
// [[Rcpp::depends(RcppArmadillo, RcppParallel)]]
// [[Rcpp::export]]
Rcpp::NumericVector SqrtCpp(Rcpp::NumericVector orig) {
// allocate the matrix we will return
NumericVector res(orig.begin(), orig.end());
// transform it
std::transform(orig.begin(), orig.end(), res.begin(), ::sqrt);
// return the new matrix
return res;
}
struct SquareRoot : public Worker
{
const RVector<double> input;
RVector<double> output;
SquareRoot(const NumericVector input, NumericVector output)
: input(input), output(output) {}
void operator()(std::size_t begin, std::size_t end) {
std::transform(input.begin() + begin,
input.begin() + end,
output.begin() + begin,
::sqrt);
}
};
// [[Rcpp::export]]
Rcpp::NumericVector SqrtCppPara(Rcpp::NumericVector x) {
// allocate the output matrix
NumericVector output(x.begin(), x.end());
// SquareRoot functor (pass input and output matrixes)
SquareRoot squareRoot(x, output);
// call parallelFor to do the work
parallelFor(0, x.length(), squareRoot);
// return the output matrix
return output;
}
struct SquareRootArma : public Worker
{
const vec& input;
vec& output;
SquareRootArma(const vec& input, vec& output)
: input(input), output(output) {}
void operator()(std::size_t begin, std::size_t end) {
for (std::size_t i = begin; i < end; ++i) {
output(i) = sqrt(input(i));
}
}
};
// [[Rcpp::export]]
vec SqrtCppArma(vec x) {
// allocate the output matrix
vec output(x.n_elem);
// SquareRoot functor (pass input and output matrixes)
SquareRootArma squareRootArma(x, output);
// call parallelFor to do the work
parallelFor(0, x.n_elem, squareRootArma);
// return the output matrix
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment