Instantly share code, notes, and snippets.

Embed
What would you like to do?
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