R/test-parallel.R

Defines functions myfun myfunpar

Documented in myfunpar

################################################################################

myfun <- function(x) x * x

################################################################################

#' Use foreach
#'
#' @param x A vector.
#' @param ncores Number of cores to use.
#'
#' @return The `x` vector, squared.
#' @export
#'
#' @import foreach
#'
#' @examples
#' Sys.getenv()
#' myfunpar(1:3, 2)
myfunpar <- function(x, ncores) {

  doParallel::registerDoParallel(cl <- parallel::makeCluster(ncores))
  on.exit(parallel::stopCluster(cl), add = TRUE)

  foreach(x_i = x) %dopar% {
    myfun(x_i)
  }
}
privefl/minipkg documentation built on Dec. 14, 2019, 7:43 p.m.