How do I set loop such that a core in my PC do half while the other the other half in R

Viewed 67

I have R scrip that simulates ARIMA data and check the same data 100 times for ARIMA order ARIMA(p, d, q). I have 2 core on the system CPU, how can I give an R command for a core to compute 1 to 50 while the second core to compute 51 to 100 simultaneously and then combine the result so that.

library(forecast)
system.time({
  for (i in 1:100) {
    a <- arima.sim(n = 50, model=list(ar = 0.8), sd = 1)
    b <- arimaorder(auto.arima(b, ic = "aicc"))
    #print(b)
  }

I am using windows 10 64 bits

1 Answers

I use foreach and doParallel libraries to divide for loop into many parts.

I believe processing is better for the computer to decide how to divide the loops between the available cores.

#…
library(parallel)
library(foreach)
library(doParallel)

#detectCores()                   ### Count number of cores available
numCores  <- 2
registerDoParallel(numCores)

#for (i in 1:100) {          ### Original For loop
foreach(i = 1:100) %dopar% { ### Replacement parallel foreach loop
    #…
}
#…
Related