问题描述
我正在开发一个主要使用 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,...)
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)
包外的代码
与上面的主要区别在于我需要:
- 通过
sfLibrary("Rcpp",character.only=TRUE)
和sfLibrary("RcppArmadillo",character.only=TRUE)
将依赖包导出到集群/核心。 - 通过
sourceCpp(code = RcppCode)
解析我的 cpp 代码,然后通过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
关于如何缩小两者之间的速度差距的任何建议都非常感谢。非常感谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)