在R包内的窗口上使用带有Rcpp功能的doParallel

问题描述 投票:0回答:1

我从此post知道,在窗口上的doParallel上使用Rcpp函数的最简单方法是构建一个程序包。我当前正在构建一个R包,我需要并行处理该包中的某些任务。我有一个Rcpp函数和一个在Rcpp函数上执行循环的R函数。这些功能将在我的包装中。如何构造R函数?根据上面的文章,使用Rcpp函数构建第一个程序包将更加容易,在R函数的第二个程序包中调用此程序包。有没有办法将两个函数放在同一个包中?

r rcpp r-package doparallel parallel-foreach
1个回答
2
投票

是的,您可以在包中放入任意数量的函数。建议所有内容都在R包中的原因是,否则您将不得不在旋转代码的每个线程或节点上编译代码。这是因为Rcpp函数是在本地编译的,并且仅具有特定于线程的指针引用。特别是,请参阅以下内容中的讨论:Using Rcpp functions inside of R's par*apply functions from the parallel package

示例包将是:

https://github.com/r-pkg-examples/rcpp-and-doparallel

尤其是R函数应正确设置并拆除并行后端。

mean_parallel_compute = function(n, mean = 0, sd = 1,
                                 n_sim = 1000,
                                 n_cores = parallel::detectCores()) {

  # Construct cluster
  cl = parallel::makeCluster(n_cores)

  # After the function is run, close the cluster.
  on.exit(parallel::stopCluster(cl))

  # Register parallel backend
  doParallel::registerDoParallel(cl)

  # Compute estimates
  estimates = foreach::foreach(i = iterators::icount(n_sim), # Perform n simulations
                               .combine = "rbind",           # Combine results
                                                             # Self-load
                               .packages = "Rcpp2doParallel") %dopar% {
    random_data = rnorm(n, mean, sd)

    result = mean_rcpp(random_data) # or use Rcpp2doParallel::mean_rcpp()
    result
  }

  estimates
}

要传递R CMD check,请确保具有以下roxygen2导入标签:

#' @importFrom foreach %dopar% foreach
#' @importFrom iterators icount
#' @importFrom doParallel registerDoParallel

此外,请确保DESCRIPTION具有以下内容:

LinkingTo: 
    Rcpp
Imports: 
    doParallel,
    Rcpp,
    foreach,
    iterators,
    parallel

一些其他示例:

© www.soinside.com 2019 - 2024. All rights reserved.