Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit df29565

Browse filesBrowse files
initial test for sum using both Rcpp and Rcpp11
1 parent e154d31 commit df29565
Copy full SHA for df29565

File tree

2 files changed

+80
-0
lines changed
Filter options

2 files changed

+80
-0
lines changed

‎testthat.R

Copy file name to clipboard
+6Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
require(methods)
2+
require(RcppParallel)
3+
require(testthat)
4+
5+
test_dir("testthat")
6+

‎testthat/test-sum.R

Copy file name to clipboard
+74Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.