- Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathinnerproduct.cpp
62 lines (48 loc) · 1.61 KB
/
innerproduct.cpp
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
52
53
54
55
56
57
58
59
60
61
/**
* @title Computing an Inner Product with RcppParallel
* @author JJ Allaire
* @license GPL (>= 2)
*/
#include<Rcpp.h>
usingnamespaceRcpp;
#include<algorithm>
// [[Rcpp::export]]
doubleinnerProduct(NumericVector x, NumericVector y) {
returnstd::inner_product(x.begin(), x.end(), y.begin(), 0.0);
}
// [[Rcpp::depends(RcppParallel)]]
#include<RcppParallel.h>
usingnamespaceRcppParallel;
structInnerProduct : publicWorker
{
// source vectors
const RVector<double> x;
const RVector<double> y;
// product that I have accumulated
double product;
// constructors
InnerProduct(const NumericVector x, const NumericVector y)
: x(x), y(y), product(0) {}
InnerProduct(const InnerProduct& innerProduct, Split)
: x(innerProduct.x), y(innerProduct.y), product(0) {}
// process just the elements of the range I have been asked to
voidoperator()(std::size_t begin, std::size_t end) {
product += std::inner_product(x.begin() + begin,
x.begin() + end,
y.begin() + begin,
0.0);
}
// join my value with that of another InnerProduct
voidjoin(const InnerProduct& rhs) {
product += rhs.product;
}
};
// [[Rcpp::export]]
doubleparallelInnerProduct(NumericVector x, NumericVector y) {
// declare the InnerProduct instance that takes a pointer to the vector data
InnerProduct innerProduct(x, y);
// call paralleReduce to start the work
parallelReduce(0, x.length(), innerProduct);
// return the computed product
return innerProduct.product;
}