I am trying to use %dopar%
to speed up my for
loop by parallelizing over multiple cores. However, I am unable to store the values that are returned. Here is a small reproducible example.
Using %dopar%
cl <- parallel::makeForkCluster(4)
doParallel::registerDoParallel(cl)
junk_parallel = seq(0,100000,1)
system.time(foreach(i=seq(0,10000,1))%dopar%{
junk_parallel[i] = sqrt(i)})
stopCluster(cl)
Output:
user system elapsed
2.536 0.148 2.690
> junk_parallel[9]
[1] 8
Using %do%
cl <- parallel::makeForkCluster(4)
doParallel::registerDoParallel(cl)
junk_parallel = seq(0,100000,1)
system.time(foreach(i=seq(0,10000,1))%do%{
junk_parallel[i] = sqrt(i)})
stopcluster(cl)
Output:
user system elapsed
2.172 0.004 2.174
> junk_parallel[9]
[1] 3
Why is that %dopar% unable to assign the right value? When to use %dopar% vs %do%?
Thanks in advance,
foreach
is much more similar tolapply
than to afor
loop.