使用内联和Rcpp调用R函数仍然与原始R代码一样慢 [英] Calling an R function using inline and Rcpp is still just as slow as original R code

查看:75
本文介绍了使用内联和Rcpp调用R函数仍然与原始R代码一样慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要评估一个需要较长循环的函数(后验分布).显然,我不想在R本身中执行此操作,因此我正在使用内联"和"Rcpp"来实现C ++.但是,我发现在每个循环使用R函数的情况下,cxx函数的运行速度与运行R代码的速度一样慢(请参见下面的代码和输出).特别是,我需要在每个循环中使用多元正态累积分布函数,因此我要使用mvtnorm软件包中的pmvnorm().

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.

如何在cxx函数中使用此R函数并加快处理速度?我想了解为什么会这样,所以将来我可以在cxxfunction中使用其他R函数.

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.

谢谢.

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 

推荐答案

您正在从Rcpp调用 R函数.

You are calling an R function from Rcpp.

那不能比直接调用R函数更快.

That cannot be faster than calling the R function directly.

您的绑定约束是您调用的函数,而不是您如何调用它. Rcpp不是某种神奇的R-to-C ++编译器.

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函数仍然与原始R代码一样慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆