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()
}
  1. Simulate n = 10000 games and create a boxplot

  2. Rewrite the loop using sapply()

results = sapply(1:n, function(i) snakes_ladders())

Is sapply() faster than a for loop?

  1. Now run in parallel using parSapply():
  2. Load the parallel package
  3. Create a cluster object using cl = makeCluster(no_of_cores). To start set no_of_cores = 2
  4. Rewrite sapply() as parSapply(). Remember that parSapply has an additional argument cl
  5. Stop the cluster using stopCluster()

Time the different versions.

library("parallel")
cl  = makeCluster(2) 
parSapply(cl, 1:4, snakes_ladders)
stopCluster(cl)
  1. If you using Linux or a Mac, take a look at mclappy(); similar to parSapply(), but without clusters.


jr-packages/efficientTutorial documentation built on Feb. 16, 2020, 7:05 p.m.