0

我正在开发一个主要使用 Rcpp、RcppArmadillo 和降雪(用于并行计算)的 R 包。它通过了“devtools::check”和“devtools::check_rhub()”。但是,我注意到我的代码在包中速度较慢,并且想缩小两者之间的差距。例如,

这是system.time()在包中运行我的代码的结果。

用户系统已过
18.72 31.12 135.56

另一方面,这是system.time()在包外正常运行我的代码的结果。

用户系统已过
4.23 2.98 102.18

此外,我还分析了 ( ) 两者,并注意到包环境中(并行计算)的profvis时间明显更长。sfLapply在这里,我简要概述了两者之间的代码结构。如果需要,我将添加一个指向我的 github 代码页的链接。

包中的代码

cpp 函数内置在 DLL 中。

foo = function(...,core=10){

  sfInit(parallel=TRUE,cpus=core) ## set number of cores for parallel computing
  sfClusterSetupRNG( type="RNGstream",seed=cluster_seed) ## set cluster seed for reproducibility

  ## read inputs and set parameters
   .
   .
   .
  sfExport(list=ls()) ##exporting parameters to cores

  node = 0:(core-1)  

  print(system.time({

  for(i in 1:iter){

       ## update_a and update_b are cpp functions built in DLL using "build and reload"
       a = sfLapply(node, update_a, a, b,...) 

       sfExport("a")
       
       b = sfLapply(node, update_b, a, b,...) 

       sfExport("b")
         .
         .
         .
   }
   }))
   return(...)
}

命名空间:

export(foo)
import(RcppArmadillo)
import(rlecuyer)
import(snow)
import(rlecuyer)
importFrom("snowfall",...)
importFrom("stats","rgamma")
importFrom("stats","runif")
importFrom(Rcpp,sourceCpp)
useDynLib(mypackage, .registration=TRUE)

包外代码

与上面的主要区别是我需要:

  1. sfLibrary("Rcpp", character.only=TRUE)通过和将依赖包导出到集群/核心sfLibrary("RcppArmadillo", character.only=TRUE)
  2. 通过解析我的 cpp 代码sourceCpp(code = RcppCode),然后通过sfClusterEval(sourceCpp(code = RcppCode))其中RcppCode包含我的所有 cpp 代码将其加载到集群/核心,如下所示,
RcppCode = '
#include <RcppArmadillo.h>
#include <Rmath.h>
using namespace Rcpp;
// Enable C++11 via this plugin (Rcpp 0.10.3 or later)
// [[Rcpp::plugins("cpp11")]]

//[[Rcpp::depends(RcppArmadillo)]]

.
.
.
// [[Rcpp::export]]
List update_a(...){
.
.
.
return List::create(...)
}
.
.
.
'

依赖包和平台的会话信息:

R version 4.0.3 (2020-10-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] RcppArmadillo_0.10.1.2.0 rlecuyer_0.3-5           Rcpp_1.0.5               snowfall_1.84-6.1        snow_0.4-3              

loaded via a namespace (and not attached):
[1] compiler_4.0.3 parallel_4.0.3 tools_4.0.3 

非常感谢有关如何缩小两者之间的速度差距的任何建议。非常感谢。

4

0 回答 0