[Rcpp-devel] cost of .Call

konrad konrad_kraemer at yahoo.de
Wed Aug 10 08:22:17 CEST 2022


Dear all,


I have a question regarding the cost of .Call. If I implement the 
rosenbrock function in R and in Rcpp. The R version is substentially 
faster then the C++ version. The Rcpp function is basically an R 
function which calls the C++ function using .Call. Which part of the 
code generates this overhead of the Rcpp function. Is it the .Call 
itself or the conversion of the types from R to Rcpp? Or have I done 
something wrong?


library(Rcpp)
library(microbenchmark)


fr <- function(x) {   ## Rosenbrock Banana function
   x1 <- x[1]
   x2 <- x[2]
   100 * (x2 - x1 * x1)^2 + (1 - x1)^2
}

sourceCpp(code = "
#include <Rcpp.h>

// [[Rcpp::export]]
double fr_rcpp(Rcpp::NumericVector x) {
   double x1 = x[0];
   double x2 = x[1];
   return 100 * (x2 - x1 * x1)*(x2 - x1 * x1) + (1 - x1)*(1 - x1);
}
")

x <- c(1, 2)
identical(fr(x), fr_rcpp(x))

r <- microbenchmark(fr(x), fr_rcpp(x))
boxplot(r)


Thank you very much for your help!


All the best,


Konrad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20220810/abe5e12f/attachment.html>


More information about the Rcpp-devel mailing list