[英]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++.显然,我不想在 R 本身中执行此操作,因此我使用“内联”和“Rcpp”来实现 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).但是,我发现在每个循环使用 R 函数的情况下,cxx 函数的运行速度与运行 R 代码一样慢(请参阅下面的代码和输出)。 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.特别是,我需要在每个循环中使用多元正态累积分布函数,因此我使用的是 mvtnorm 包中的 pmvnorm()。
How can I use this R function within the cxxfunction and speed things up?如何在 cxxfunction 中使用这个 R 函数并加快速度? I'd like to understand why this is happening so I can use other R functions within cxxfunction in the future.我想了解为什么会发生这种情况,以便将来可以在 cxxfunction 中使用其他 R 函数。
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
You are calling an R function from Rcpp.您正在从 Rcpp 调用R 函数。
That cannot be faster than calling the R function directly.这不会比直接调用 R 函数快。
Your binding constraint is the function you call and not how you call it.您的绑定约束是您调用的函数,而不是您调用它的方式。 Rcpp is not some magic R-to-C++ compiler. Rcpp 不是一些神奇的 R-to-C++ 编译器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.