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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…