-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.R
51 lines (38 loc) · 1.08 KB
/
main.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
library(Rcpp)
library(RcppParallel)
# https://gallery.rcpp.org/articles/parallel-vector-sum/
cppFunction('
// [[Rcpp::depends(RcppParallel)]]
#include <RcppParallel.h>
using namespace RcppParallel;
struct Sum : public Worker
{
// source vector
const RVector<double> input;
// accumulated value
double value;
// constructors
Sum(const NumericVector input) : input(input), value(0) {}
Sum(const Sum& sum, Split) : input(sum.input), value(0) {}
// accumulate just the element of the range
void operator()(std::size_t begin, std::size_t end) {
value += std::accumulate(input.begin() + begin, input.begin() + end, 0.0);
}
// join my value with that of another Sum
void join(const Sum& rhs) {
value += rhs.value;
}
};
// [[Rcpp::export]]
double parallelVectorSum(NumericVector x) {
// declare the SumBody instance
Sum sum(x);
// call parallel_reduce to start the work
parallelReduce(0, x.length(), sum);
// return the computed sum
return sum.value;
}
')
# allocate a vector
v <- as.numeric(c(1:10000000))
parallelVectorSum(v)