The tictoc package implements this exact functionality, so the timing of sequential or nested timings is stored in a list and for subsequent analysis.
For example, to time each iteration of a loop and analyze the results later, use the log
functionality.
library(tictoc)
tic.clearlog()
for (x in 1:10) {
# passing x to tic() makes it a label at time of the matching toc() call.
tic(x)
Sys.sleep(1)
# When log = TRUE, toc() pushes the measured timing to a list
# quiet = TRUE prevents from printing the timing
toc(log = TRUE, quiet = TRUE)
}
Fetch the results of toc()
as formatted text for printing.
log.txt <- tic.log(format = TRUE)
Extract the list containing measurements in raw format.
log.lst <- tic.log(format = FALSE)
Since the data is already extracted, clear the tictoc log.
tic.clearlog()
Convert the list elements to timings.
Each element of the list has a start (tic
) and end (toc
) timestamp.
timings <- unlist(lapply(log.lst, function(x) x$toc - x$tic))
Compute the average loop time.
mean(timings)
# [1] 1.001
Print the text output - note that the prefixes are the values of x
.
writeLines(unlist(log.txt))
# 1: 1.002 sec elapsed
# 2: 1 sec elapsed
# 3: 1.002 sec elapsed
# 4: 1.001 sec elapsed
# 5: 1.001 sec elapsed
# 6: 1.001 sec elapsed
# 7: 1.001 sec elapsed
# 8: 1.001 sec elapsed
# 9: 1.001 sec elapsed
# 10: 1 sec elapsed