Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Created January 13, 2026 23:52
Show Gist options
  • Select an option

  • Save abikoushi/f9b2ec89b9f0ee440ed13536c9b94486 to your computer and use it in GitHub Desktop.

Select an option

Save abikoushi/f9b2ec89b9f0ee440ed13536c9b94486 to your computer and use it in GitHub Desktop.
Try RcppParallel
// [[Rcpp::depends(RcppParallel)]]
#include <RcppParallel.h>
#include <Rcpp.h>
#include <numeric>
using namespace Rcpp;
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 I've been asked to
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 Sum instance
Sum sum(x);
// call parallel_reduce to start the work
parallelReduce(0, x.length(), sum);
// return the computed sum
return sum.value;
}
library(Rcpp)
library(RcppParallel)
sourceCpp("R/cpp/parallelreduce.cpp")
# defaultNumThreads()
setThreadOptions(numThreads = 4)
m <- rnorm(1e+8)
# ensure that serial and parallel versions give the same result
# compare performance of serial and parallel
library(rbenchmark)
res <- benchmark(sum(m),
parallelVectorSum(m),
order="relative")
res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment