vignettes/06b-R_Profiling_code.Rmd
06b-R_Profiling_code.Rmd
In general, the usual claim is to worry about ‘execution speed later’
This is not 100% true with R
If you use vectorization (no or few loops), and these packages listed here, then you will have a good start
AFTER that, then you can use several great tools:
profvis
package (built into the latest Rstudio)microbenchmark::microbenchmark()
microbenchmark::microbenchmark(
loop = {
a <- vector()
for (i in 1:1000) a[i] <- runif(1)
},
vectorized = {
a <- runif(1000)
}
)
## Unit: microseconds
## expr min lq mean median uq max neval
## loop 2935.292 3130.147 4037.20882 3487.556 4227.313 16652.65 100
## vectorized 27.343 27.944 31.33944 29.146 30.498 95.85 100
If you have Rstudio version >=0.99.1208
, then it has profiling as a menu item.
alternatively, we wrap any block of code with profvis
This can be a spades()
call, so it will show you the entire model:
spades
callTry it:
mySim <- simInit(
times = list(start = 0.0, end = 2.0, timeunit = "year"),
params = list(
.globals = list(stackName = "landscape", burnStats = "nPixelsBurned")
),
modules = list("randomLandscapes", "fireSpread", "caribouMovement"),
paths = list(modulePath = system.file("sampleModules", package = "SpaDES"))
)
profvis::profvis({spades(mySim)})
If you have used these tools, then: