3

I am looking for an elegant way of timing execution of R chunk preferably running the chunk multiple times automatically in background. (Magic function %%timeit in Python notebook does exactly that)

I know there are several ways of timing an R function or bunch of R code and there are few SO questions on that as well. All the methods are described in this article too.

However, most of them do not replicate the r code and ones which have option to replicate (like system.time or mircobenchbark) are ideal for using on a function but not on a chunk of code. (or may be I do not understand it right)

tictoc works pretty well for me except it will give the run time for only single execution but does not have option to run like 1000 times and averaging the run time. (again what %%timeit does)

PagMax
  • 8,088
  • 8
  • 25
  • 40
  • 1
    Just wrap your code in curly brackets `{ your code here }` and `system.time` or `microbenchmark` will be fine to take it. Like `system.time({block of code})`, it is fine if it spans multiple lines. You could also wrap it in a function and call the function by name for a cleaner testing interface. – lmo Jul 06 '17 at 12:27
  • Thanks @lmo. Yes that is what I thought would be the way to go about it. I was hoping there would be more elegant way. Glad to have that confirmation now. – PagMax Jul 06 '17 at 12:31
  • It's possible a fancier method with a package exists, but this is the way that I do it. Pretty simple to implement. You might take a look at the `profVis` package. If I remember right, it produces graphs and so on that might be appealing. – lmo Jul 06 '17 at 12:36

1 Answers1

2

With tictoc it is possible to record the timing in a loop and average the results.

library(tictoc)
tic.clearlog()
for (x in 1:10) {
    # passing x to tic() makes its value to become 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