A parallelized version of for loop
# A general procedure for parallelized for loop
# Even with 4 cores, the gain is interesting
# Let take this example
A <- 1:10000
system.time({
out <- NULL
for (i in A) {
# I do something with i, an element of A
# this part must be copied
j <- sqrt(i)
out <- c(out, j)
# I go out of the loop
}
})
library("parallel")
system.time({
B <- split(A, cut(A, detectCores(), labels = FALSE))
out <- unname(unlist(mclapply(B, FUN= function(Bi) {
outi <- NULL
for (i in Bi) {
# I do something with i, an element of A
j <- sqrt(i)
outi <- c(outi, j)
# I go out of the loop
}
return(outi)
})))
})
# Even with 4 cores, the gain is interesting
# Let take this example
A <- 1:10000
system.time({
out <- NULL
for (i in A) {
# I do something with i, an element of A
# this part must be copied
j <- sqrt(i)
out <- c(out, j)
# I go out of the loop
}
})
library("parallel")
system.time({
B <- split(A, cut(A, detectCores(), labels = FALSE))
out <- unname(unlist(mclapply(B, FUN= function(Bi) {
outi <- NULL
for (i in Bi) {
# I do something with i, an element of A
j <- sqrt(i)
outi <- c(outi, j)
# I go out of the loop
}
return(outi)
})))
})
Commentaires
Enregistrer un commentaire