This is really blowing my mind. The basic loop takes like 8 seconds on my computer:
system.time({
x <- 0
for (p in 1:2) {
for (i in 1:500) {
for (j in 1:5000) {
x <- x + i * j
}
}
}
})
x
Whereas if I use foreach
in non-parallel mode, it does take only 0.7 secs!!!
system.time({
x <- 0
foreach(p = 1:2, .combine = rbind) %do%
for (i in 1:500) {
for (j in 1:5000) {
x <- x + i * j
}
}
})
x
The result is the same, but foreach
was somehow able to reach it much faster than basic R! Where is the inefficiency of basic R?
How is this possible?
In fact, I got complete opposite result compared to this one: Why is foreach() %do% sometimes slower than for?
make.codeBuf
– Butacainecompile::cmpfun
, will the resultant function be as fast asforeach
? – Phebephedra