Skip to content

Instantly share code, notes, and snippets.

@shabbychef
Last active March 25, 2016 18:18
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 shabbychef/9c2ed6b2ee92f104a8b1 to your computer and use it in GitHub Desktop.
Save shabbychef/9c2ed6b2ee92f104a8b1 to your computer and use it in GitHub Desktop.
y u no work, RcppParallel?
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::depends(RcppParallel)]]
#include <RcppParallel.h>
using namespace RcppParallel;
// accumulate # of elements seen on the input iterator.
void accum_nel_int(RVector<double>::const_iterator vecit,
RVector<double>::const_iterator end,
RVector<int>::iterator xret) {
for (;vecit != end;++vecit) { *xret += 1; }
}
void join_em_int(RVector<int> lhs, const RVector<int> rhs) {
lhs[0] += rhs[0];
}
struct NEL_int : public Worker
{
// source vector
const RVector<double> input;
// accumulated value
RVector<int> output;
// constructors
NEL_int(const NumericVector input, IntegerVector output) : input(input), output(output) {}
NEL_int(const NEL_int& othr, Split) : input(othr.input), output(othr.output) {}
// accumulate just the element of the range I've been asked to
void operator()(std::size_t begin, std::size_t end) {
accum_nel_int(input.begin() + begin, input.begin() + end, output.begin());
}
// join my value with that of another NEL_int
void join(const NEL_int& rhs) {
join_em_int(output,rhs.output);
}
};
// dumb example counting # of elements on input:
// [[Rcpp::export]]
IntegerVector dumbCount_int(NumericVector x) {
// allocate the output
IntegerVector output(1);
// declare the instance
NEL_int wrkr(x,output);
// call parallel_reduce to start the work
parallelReduce(0, x.length(), wrkr, 5000);
// return the computed number of non-na elements
return output;
}
// in R do:
// library(Rcpp)
// source('yunoparallel.cpp')
// x <- rnorm(1e5)
// dumbCount_int(x)
// dumbCount_int(x)
// # fine, right? no.
// replicate(10,dumbCount_int(x))
// sd(replicate(100,dumbCount_int(x)))
//for vim modeline: (do not edit)
// vim:ts=4:sw=4:tw=79:fdm=marker:fmr=FOLDUP,UNFOLD:cms=//%s:syn=cpp:ft=cpp:ai:si:et:cin:nu:fo=croql:cino=p0t0c5(0:
library(Rcpp)
source('yunoparallel.cpp')
x <- rnorm(1e5)
dumbCount_int(x)
dumbCount_int(x)
# fine, right? no.
replicate(10,dumbCount_int(x))
sd(replicate(100,dumbCount_int(x)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment