celestialgod

RcppParallel with RcppArmadillo

Aug 6th, 2015
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.54 KB | None | 0 0
  1. ## installation
  2. library(devtools)
  3. install_github("RcppCore/RcppParallel")
  4.  
  5. ## code
  6. library(Rcpp)
  7. library(RcppArmadillo)
  8. library(RcppParallel)
  9. sourceCpp(code = '
  10. // [[Rcpp::depends(RcppArmadillo)]]
  11. // [[Rcpp::depends(RcppParallel)]]
  12. #define ARMA_DONT_USE_CXX11
  13. #include <RcppArmadillo.h>
  14. #include <RcppParallel.h>
  15. using namespace Rcpp;
  16. using namespace arma;
  17. using namespace RcppParallel;
  18.  
  19. // [[Rcpp::export]]
  20. vec times_two_f1(NumericVector xr) {
  21.  vec x(xr.begin(), xr.size()), y(xr.size());
  22.  for(uword i = 0; i < x.n_elem; i++) y(i) = x(i)*2;
  23.  return y;
  24. }
  25.  
  26. struct TimesTwo: public Worker {
  27.  vec& input;
  28.  vec& output;
  29.  TimesTwo(vec& input, vec& output) : input(input), output(output) {}
  30.  void operator()(std::size_t begin, std::size_t end) {
  31.    for(std::size_t i = begin; i < end; i++) output(i) = input(i)*2;
  32.  }
  33. };
  34.  
  35. // [[Rcpp::export]]
  36. vec times_two_f2(NumericVector xr) {
  37.  vec x(xr.begin(), xr.size()), y(xr.size());
  38.  TimesTwo timesTwo(x, y);
  39.  parallelFor(0, x.n_elem, timesTwo);
  40.  return y;
  41. }
  42.  
  43. // [[Rcpp::export]]
  44. vec times_two_f3(NumericVector xr) {
  45.  vec x(xr.begin(), xr.size());
  46.  return x*2;
  47. }')
  48.  
  49. library(rbenchmark)
  50. x = rnorm(3e7)
  51. benchmark(cpp = times_two_f1(x),
  52.     cppParallel = times_two_f2(x),
  53.     Armadillo = times_two_f3(x),
  54.     columns=c("test", "replications","elapsed", "relative"),
  55.     replications=20, order="relative")
  56. #          test replications elapsed relative
  57. # 2 cppParallel           20    4.06    1.000
  58. # 3   Armadillo           20    4.39    1.081
  59. # 1         cpp           20    4.70    1.158
Advertisement
Add Comment
Please, Sign In to add comment