Skip to content

Instantly share code, notes, and snippets.

@christophergandrud
Created March 19, 2021 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophergandrud/d39315e3b98381dcfe3ee840f4c6db39 to your computer and use it in GitHub Desktop.
Save christophergandrud/d39315e3b98381dcfe3ee840f4c6db39 to your computer and use it in GitHub Desktop.
#' Multi-core replicate. From the rethinking package:
#' <https://github.com/rmcelreath/rethinking/blob/3b48ec8dfda4840b9dce096d0cb9406589ef7923/R/utilities.r#L206>
#'
#' @param n integer: the number of replications.
#' @param expr the expression (a language object, usually a call) to evaluate repeatedly.
#' @param refresh status update refresh interval
#' @param mc.cores number of cores to use
#'
#' @importFrom parallel mclapply
#' @export
mcreplicate <- function(n, expr, refresh = 0.1, mc.cores = 2) {
require(parallel)
show_progress <- function(i) {
intervaln <- floor(n * refresh)
if (floor(i/intervaln) == i/intervaln) {
cat(paste("[", i, "/", n, "]\r"))
}
}
result <- simplify2array(mclapply(1:n, eval.parent(substitute(function(i, ...) {
if (refresh > 0) show_progress(i)
expr
})), mc.cores = mc.cores))
if (refresh > 0)
cat("\n")
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment