优化 RCPP 代码

optimizing rcpp code

本文关键字:代码 RCPP 优化      更新时间:2023-10-16

我开始尝试使用rcpp来提高R中for循环的速度,其中每次迭代都依赖于前一次(即没有简单的矢量化)。我当前的代码(如下)比R快一点,但没有我想象的那么快。 下面的代码中是否有明显的低效率,有人可以发现?任何一般(或具体)建议都会有所帮助。

UpdateInfections <- cxxfunction(signature(pop ="data.frame",inds="integer",alpha="numeric",t="numeric"), '
DataFrame DF(pop);
IntegerVector xinds(inds);
NumericVector inf_time = DF["inf.time"];
IntegerVector loc = DF["loc"] ;
IntegerVector Rind = DF["R.indiv"] ;
NumericVector infector = DF["infector"] ;
IntegerVector vac = DF["vac"] ;
NumericVector wts(loc.size());
double xt = Rcpp::as<double>(t);
double xalpha = Rcpp::as<double>(alpha);

RNGScope scope;         // Initialize Random number generator
Environment base("package:base");
Function sample = base["sample"];
int n = loc.size();
int i;int j;int k;
int infsize = xinds.size();
for (i=0;i<infsize;i++) {
   int infpoint = xinds[i]-1;
    NumericVector inf_times_prop(Rind[infpoint]);
    NumericVector inf_me(Rind[infpoint]);
for (j=0; j<n;j++){
  if (j == infpoint){
wts[j] = 0.0;
  } else if (loc[j] == loc[infpoint]){
    wts[j] = 1.0;
  } else {
wts[j] = xalpha;
  }
}
inf_me = sample(n,Named("size",Rind[infpoint]),Named("prob",wts));
//Note that these will be shifted by one
for (k=0;k<Rind[infpoint];k++){
  inf_times_prop[k] = floor(::Rf_rlnorm(1.6,.6) + 0.5 + xt);
  if (inf_times_prop[k] < inf_time[inf_me[k]-1] && vac[inf_me[k]-1] == 0){
    inf_time[inf_me[k]-1] = inf_times_prop[k];
    infector[inf_me[k]-1] = inf_me[k];
  }
}
}
// create a new data frame
Rcpp::DataFrame NDF =
Rcpp::DataFrame::create(Rcpp::Named("inf.time")=inf_time,
                        Rcpp::Named("loc")=loc,
                        Rcpp::Named("R.indiv")=Rind,
                        Rcpp::Named("infector")=infector,
                        Rcpp::Named("vac")=vac);
return(NDF);
' , plugin = "Rcpp" )

我们现在实际上正在为 RcppArmadillo 开发一个纯C++示例函数。 http://permalink.gmane.org/gmane.comp.lang.r.rcpp/4179 或 http://permalink.gmane.org/gmane.comp.lang.r.rcpp 此处查看此处以获取更新。

您正在回调 R。这不可能是一个纯粹的C++解决方案。

你的例子也很长,太长了。 我建议分析和优化单个部分。 唉,仍然没有完全免费的午餐。