mrc-ide / drjacoby

Flexible Markov chain monte carlo via reparameterization
https://mrc-ide.github.io/drjacoby/
Other
12 stars 6 forks source link

Passing c++ or R function as argument #1

Closed pwinskill closed 5 years ago

pwinskill commented 5 years ago

Some code testing the possibility of passing a Rcpp function as an argument to an Rcpp function and also a speed comparison compared to jumping in and out to the equivalent R function each time:


library(Rcpp)
library(microbenchmark)
library(ggplot2)

cppFunction('double m(std::vector<double> y){
  double s;
  for(unsigned int i = 0; i < y.size(); i++){
    s += y[i];
  }
  return s / y.size();
}')
cppFunction('NumericVector t2(Function f1, int N, std::vector<double> y){
  NumericVector x;
  for(int i = 0; i < N; i++){
    x = f1(y);
  }
  return x;
}')

bm <- microbenchmark(passing_R = t2(mean, 10000, 1:10),
                     passing_cpp = t2(m, 10000, 1:10),
                     times = 20)

ggplot(data = bm, aes(y = time, x = expr, colour = expr)) +
  geom_violin()

bm2 <- microbenchmark(mean_R = mean(1:100),
                     mean_cpp = m(1:100),
                     times = 20)
ggplot(data = bm2, aes(y = time, x = expr, colour = expr)) +
  geom_violin()
pwinskill commented 5 years ago

The raw R mean function is slower than the raw c++ mean function, so not sure how much of the difference in the timings above is due to that and how much is due to jumping back and forth between c++ and R