I am trying to use the doSMP package that provides a parallel backend for the foreach package.
Can you point out what I do wrong? Indeed, using foreach in that way increases significantly the computing time...
#------register doSMP to be used with foreach------
library(doSMP)
w <- startWorkers(4)
registerDoSMP(w)
#--------------------------------------------------
#------A simple function------
sim <- function(a, b)
{
return(10 * a + b)
}
avec <- 1:200
bvec <- 1:400
#-----------------------------
#------The naive method------
ptime <- system.time({
mat <- matrix(NA, nrow=length(avec), ncol=length(bvec))
for(i in 1:length(avec))
{
for(j in 1:length(bvec))
{
mat[i, j] <- sim(avec[i], bvec[j])
}
}
})[3]
ptime
elapsed
0.36
#----------------------------
#------Using foreach------
ptime <- system.time({
mat2 <- foreach(b=bvec, .combine="cbind") %:%
foreach(a=avec, .combine="c") %dopar%
{
sim(a, b)
}
})[3]
ptime
elapsed
86.98
#-------------------------
EDIT
That question is very very similar to this one and has been migrated from stats.stackexchange.