[英]How can I call a user defined R function in parallel from within an Rcpp function?
我正在編寫一個使用用戶定義的 R 函數的 R package。 這些函數需要在 Rcpp function 中多次評估。
我看到了兩條出路:
1- Create several R sessions using RInline, evaluate the function with different arguments in each R session then gather these results?
2- Write a wrapper around the user-defined R function so that it is vectorized and evaluates the different inputs of the R function in parallel. 然后將此 function 傳遞給 Rcpp,希望在調用 R function 時仍將並行運行。
我不確定這些方法是否可行。 嘗試第二個很容易。 但也許有人有更好的解決方案。
我想我有第二個工作選擇。 無論如何,感謝您的快速回復。 我也認為第一種方法可以奏效。 但這足以滿足我的目的。 請參見下面的示例:
library(Rcpp)
library(future.apply)
userfunc<-function(x){
Sys.sleep(1)
return(x)
}
wrapperufpar<-function(xvec){
plan(multisession)
future_sapply(xvec, userfunc)
}
cppFunction('NumericVector cppfunc(NumericVector xvec, Function ufunc) {
NumericVector out(xvec.length());
for (int i=0;i<xvec.length();i++){
out(i)=as<double>(ufunc(xvec(i)));
}
return out;
}')
cppFunction('NumericVector cppfuncpar(NumericVector xvec, Function ufuncw) {
NumericVector out=as<NumericVector>(ufuncw(xvec));
return out;
}')
cppfunc(1:10, userfunc)
[1] 1 2 3 4 5 6 7 8 9 10
cppfuncpar(1:10, wrapperufpar)
[1] 1 2 3 4 5 6 7 8 9 10
microbenchmark::microbenchmark(wrapperufpar(1:10),
sapply(1:10, userfunc),
cppfunc(1:10, userfunc),
cppfuncpar(1:10, wrapperufpar),
times=10)
單位:秒
expr min lq mean median
wrapperufpar(1:10) 4.372158 4.456099 4.488181 4.477420
sapply(1:10, userfunc) 10.002320 10.003834 10.005113 10.004944
cppfunc(1:10, userfunc) 10.002743 10.004133 10.005217 10.004824
cppfuncpar(1:10, wrapperufpar) 4.434338 4.475258 4.490961 4.491418
uq max neval
4.548762 4.564422 10
10.006996 10.007854 10
10.006614 10.008436 10
4.509277 4.545920 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.