|
| 1 | +context( "sum" ) |
| 2 | + |
| 3 | +code <- ' |
| 4 | +#include <Rcpp.h> |
| 5 | +#include <RcppParallel.h> |
| 6 | +
|
| 7 | +// [[Rcpp::depends(RcppParallel)]] |
| 8 | +using namespace RcppParallel; |
| 9 | +using namespace Rcpp; |
| 10 | +
|
| 11 | +struct Sum : public Worker |
| 12 | +{ |
| 13 | + // source vector |
| 14 | + const RVector<double> input; |
| 15 | + |
| 16 | + // accumulated value |
| 17 | + double value; |
| 18 | + |
| 19 | + // constructors |
| 20 | + Sum(const NumericVector input) : input(input), value(0) {} |
| 21 | + Sum(const Sum& sum, Split) : input(sum.input), value(0) {} |
| 22 | + |
| 23 | + // accumulate just the element of the range I have been asked to |
| 24 | + void operator()(std::size_t begin, std::size_t end) { |
| 25 | + value += std::accumulate(input.begin() + begin, input.begin() + end, 0.0); |
| 26 | + } |
| 27 | + |
| 28 | + // join my value with that of another Sum |
| 29 | + void join(const Sum& rhs) { |
| 30 | + value += rhs.value; |
| 31 | + } |
| 32 | +}; |
| 33 | +
|
| 34 | +// [[Rcpp::export]] |
| 35 | +double parallelVectorSum(NumericVector x) { |
| 36 | + |
| 37 | + // declare the SumBody instance |
| 38 | + Sum sum(x); |
| 39 | + |
| 40 | + // call parallel_reduce to start the work |
| 41 | + parallelReduce(0, x.length(), sum); |
| 42 | + |
| 43 | + // return the computed sum |
| 44 | + return sum.value; |
| 45 | +} |
| 46 | +
|
| 47 | +// [[Rcpp::export]] |
| 48 | +double vectorSum(NumericVector x) { |
| 49 | + return std::accumulate(x.begin(), x.end(), 0.0); |
| 50 | +} |
| 51 | +
|
| 52 | +' |
| 53 | + |
| 54 | +test_that( "sum works with Rcpp", { |
| 55 | + Rcpp::sourceCpp( code = code ) |
| 56 | + |
| 57 | + v <- as.numeric(c(1:10000000)) |
| 58 | + |
| 59 | + expect_equal( |
| 60 | + vectorSum(v), |
| 61 | + parallelVectorSum(v) |
| 62 | + ) |
| 63 | +}) |
| 64 | + |
| 65 | +test_that( "sum works with Rcpp11", { |
| 66 | + attributes::sourceCpp( code = code) |
| 67 | + |
| 68 | + v <- as.numeric(c(1:10000000)) |
| 69 | + |
| 70 | + expect_equal( |
| 71 | + vectorSum(v), |
| 72 | + parallelVectorSum(v) |
| 73 | + ) |
| 74 | +}) |
0 commit comments