Parallelize 'foreach' functions
Henrik Bengtsson
Source:vignettes/futurize-51-foreach.md
futurize-51-foreach.RmdThe futurize package allows you to easily turn
sequential code into parallel code by piping the sequential code to the
futurize() function. Easy!
+
=

Introduction
This vignette demonstrates how to use this approach to parallelize
functions such as foreach() and times() of the
foreach
package. For example, consider:
This foreach() construct is resolved sequentially. We
can use the futurize package to tell
foreach to hand over the orchestration of parallel
tasks to futureverse. All we need to do is to pass the expression to
futurize() as in:
library(futurize)
library(foreach)
xs <- 1:1000
ys <- foreach(x = xs) %do% slow_fcn(x) |> futurize()This will distribute the calculations across the available parallel workers, given that we have set parallel workers, e.g.
plan(multisession)The built-in multisession backend parallelizes on your
local computer and it works on all operating systems. There are other parallel
backends to choose from, including alternatives to parallelize
locally as well as distributed across remote machines, e.g.
plan(future.mirai::mirai_multisession)and
plan(future.batchtools::batchtools_slurm)Here is another example that parallelizes times() of the
foreach package via the futureverse ecosystem:
Supported Functions
The futurize() function supports parallelization of the
following foreach functions:
foreach(...) %do% { ... }-
times(...) %do% { ... }withseed = TRUEas the default