Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

Calling an R function using inline and Rcpp is still just as slow as original R code

I need to evaluate a function (posterior distribution) which requires long loops. Clearly I don't want to do this within R itself, and so I'm using "inline" and "Rcpp" to implement C++. However, I'm finding that in the case where each loop uses an R function, the cxxfunction is running just as slow as running the R code (see code and output below). In particular, I'm needing to use a multivariate normal cumulative distribution function within each loop, and so I'm using pmvnorm() from the mvtnorm package.

How can I use this R function within the cxxfunction and speed things up? I'd like to understand why this is happening so I can use other R functions within cxxfunction in the future.

Thank you.

test <- cxxfunction(
  signature(Num="integer",MU="numeric",Sigma="numeric"),
  body='
  RNGScope scope;

  Environment stats("package:mvtnorm");
  Function pmvnorm = stats["pmvnorm"];

  int num = Rcpp::as<int>(Num);
  NumericVector Ret(1);
  NumericMatrix sigma(Sigma);
  NumericVector mu(MU);
  NumericVector zeros(2);

for(int i = 0; i < num; i++)
{
  Ret = pmvnorm(Named("upper",zeros),Named("mean",MU),Named("sigma",sigma));
}
return Ret;
',plugin="Rcpp"
)

system.time(
test(10000,c(1,2),diag(2))
)
    user  system elapsed 
    5.64    0.00    5.75 

system.time(
for(i in 1:10000){
pmvnorm(upper=c(0,0),mean=c(1,2),sigma=diag(2))
}
)
   user  system elapsed 
   5.46    0.00    5.57 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are calling an R function from Rcpp.

That cannot be faster than calling the R function directly.

Your binding constraint is the function you call and not how you call it. Rcpp is not some magic R-to-C++ compiler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...