Skip to content

Commit 5e61e85

Browse files
committed
add a 'map-reduce' example; fix
1 parent 6d46f16 commit 5e61e85

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

examples/boost-simd-map-reduce.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// [[Rcpp::depends(RcppParallel)]]
2+
#define RCPP_PARALLEL_USE_SIMD
3+
#include <RcppParallel.h>
4+
using namespace RcppParallel;
5+
6+
#include <Rcpp.h>
7+
using namespace Rcpp;
8+
9+
class SumOfSquaresReducer
10+
{
11+
public:
12+
13+
explicit SumOfSquaresReducer(double mean)
14+
: mean_(mean)
15+
{}
16+
17+
template <typename T>
18+
void map(const T& self, T* pBuffer)
19+
{
20+
*pBuffer += boost::simd::sqr(self - mean_);
21+
}
22+
23+
template <typename T, typename U>
24+
void reduce(const T& data, U* pBuffer)
25+
{
26+
*pBuffer += boost::simd::sum(data);
27+
}
28+
29+
private:
30+
double mean_;
31+
};
32+
33+
// [[Rcpp::export]]
34+
double simdVar(NumericVector x)
35+
{
36+
double total = simdReduce(x.begin(), x.end(), 0.0, simd_ops::plus());
37+
double n = x.size();
38+
double mean = total / n;
39+
40+
double ssq = simdMapReduce(x.begin(), x.end(), 0.0, SumOfSquaresReducer(mean));
41+
42+
return ssq / (n - 1);
43+
}
44+
45+
/*** R
46+
x <- rnorm(1024 * 10000)
47+
var(x)
48+
simdVar(x)
49+
library(microbenchmark)
50+
microbenchmark(var(x), simdVar(x))
51+
*/

inst/include/RcppParallel/simd/algorithm.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ U simdMapReduce(const T* it, const T* end, U init, MapReducer mapper)
6060
for (; it != aligned_end; it += N)
6161
mapper.map(boost::simd::aligned_load<vT>(it), &buffer);
6262

63-
// Reduce our buffer, and join it with the initial value
64-
mapper.map(mapper.reduce(buffer), &init);
63+
// Reduce the buffer, joining it into the scalar vale
64+
mapper.reduce(buffer, &init);
6565

6666
// Leftover unaligned region
6767
for (; it != end; ++it)

0 commit comments

Comments
 (0)