memoise package can be very handy for caching the results of slow calculations. In interactive work, the slowest calculations can be reading data, so that is demonstrated here. The
microbenchmark package shows timing results.
Methods and results
First, load the package being tested, and also a benchmarking package.
1 2 library(memoise) library(microbenchmark)
Test conventional function
The demonstration will be for reading a CTD file.
Memoise the function
read.oce() is simple
1 r <- memoise(read.oce)
Measure the speed of memoised code
1 microbenchmark(d <- r("/data/arctic/beaufort/2012/d201211_0002.cnv"))
In this example, the speedup was by a factor of about 3000.
The operation tested here is quick enough for interactive work, but this is a 1-dbar file, and the time would be increased to several seconds for raw CTD data, and increased to perhaps a half minute or so if a whole section of CTD profiles is to be read. Using
memoise() would reduce that half minute to a hundredth of a second – easily converting an annoyingly slow operation to what feels like zero time in an interactive session.