Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## installation
- library(devtools)
- install_github("RcppCore/RcppParallel")
- ## code
- library(Rcpp)
- library(RcppArmadillo)
- library(RcppParallel)
- sourceCpp(code = '
- // [[Rcpp::depends(RcppArmadillo)]]
- // [[Rcpp::depends(RcppParallel)]]
- #define ARMA_DONT_USE_CXX11
- #include <RcppArmadillo.h>
- #include <RcppParallel.h>
- using namespace Rcpp;
- using namespace arma;
- using namespace RcppParallel;
- // [[Rcpp::export]]
- vec times_two_f1(NumericVector xr) {
- vec x(xr.begin(), xr.size()), y(xr.size());
- for(uword i = 0; i < x.n_elem; i++) y(i) = x(i)*2;
- return y;
- }
- struct TimesTwo: public Worker {
- vec& input;
- vec& output;
- TimesTwo(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) = input(i)*2;
- }
- };
- // [[Rcpp::export]]
- vec times_two_f2(NumericVector xr) {
- vec x(xr.begin(), xr.size()), y(xr.size());
- TimesTwo timesTwo(x, y);
- parallelFor(0, x.n_elem, timesTwo);
- return y;
- }
- // [[Rcpp::export]]
- vec times_two_f3(NumericVector xr) {
- vec x(xr.begin(), xr.size());
- return x*2;
- }')
- library(rbenchmark)
- x = rnorm(3e7)
- benchmark(cpp = times_two_f1(x),
- cppParallel = times_two_f2(x),
- Armadillo = times_two_f3(x),
- columns=c("test", "replications","elapsed", "relative"),
- replications=20, order="relative")
- # test replications elapsed relative
- # 2 cppParallel 20 4.06 1.000
- # 3 Armadillo 20 4.39 1.081
- # 1 cpp 20 4.70 1.158
Advertisement
Add Comment
Please, Sign In to add comment