优化 RCPP 代码
optimizing rcpp code
我开始尝试使用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++解决方案。
你的例子也很长,太长了。 我建议分析和优化单个部分。 唉,仍然没有完全免费的午餐。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么我的 Rcpp 代码比 glmnet 慢得多?
- R-使用RCPP时如何并行C 代码
- 为什么我的RCPP代码给出意外的所有整数值输出
- 如何在代码中使用 Rcpp::Blocks IDE
- Rcpp:从全局环境调用一个R函数,并在C++代码中使用它
- R -RCPP-如何在C 代码中使用分布功能
- 将 Rcpp 与 C 代码链接,以实现自适应城域拒绝采样
- 优化 RCPP 代码
- RCPP代码崩溃
- RCpp:如何在不重新启动R的情况下重新加载重新编译的C++代码
- r语言 - 在 Windows 上使用 Rcpp 创建.dll文件并编译C++代码
- Rcpp:将数据帧与 Rcpp(内联)一起使用时推荐的代码结构
- OpenMP 在 SEIR 模型的 Rcpp 代码中生成段错误
- 我可以像 Rcpp 在 Julia 中的 stop() 一样在 c 代码中抛出错误吗
- 使用Rcpp使用最新的QuantLib代码
- 加载Rcpp并运行示例代码
- 运行编译的c++代码与Rcpp
- 元素矩阵乘法:R与Rcpp(如何加速这段代码?)
- 使用RStudio在R包中编译Rcpp代码时出错