Do you want in-house training? Please get in contact
In the efficientTutorial package there is a function, snake_ladders()
, that simulates a
game of snakes and ladders (for a single player)^[This example
is based on the real game after a particularly long and boring session with my 5 year old son]:
library("efficientTutorial") snakes_ladders()
The return value is the number of rolls required to finish the game. We can simulate multiple games via
n = 10 results = numeric(n) for (i in 1:n) { results[i] = snakes_ladders() }
Simulate n = 10000
games and create a boxplot
Rewrite the loop using sapply()
results = sapply(1:n, function(i) snakes_ladders())
Is sapply()
faster than a for loop?
parSapply()
:cl = makeCluster(no_of_cores)
. To start set
no_of_cores = 2
sapply()
as parSapply()
. Remember that parSapply
has an additional argument cl
stopCluster()
Time the different versions.
library("parallel") cl = makeCluster(2) parSapply(cl, 1:4, snakes_ladders) stopCluster(cl)
mclappy()
; similar to parSapply()
,
but without clusters.Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.