2

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,

5

1 Answer 1

2

The computation in a parallel loop is in it's own instance. You're trying to assign to a global that foreach does not have access to. Try this:

cl <- parallel::makeForkCluster(4)
doParallel::registerDoParallel(cl)
junk_parallel <- foreach(i=seq(0,10000,1)) %dopar% {
  sqrt(i)}
stopCluster(cl)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.