## 11.3 Report how much time each chunk takes to run

By default, knitr provides a text-based progress bar to show you the knitting progress. If you want more precise timing information about the chunks, you may register a custom chunk hook to record the time for each chunk. Here is an example hook:

knitr::knit_hooks$set(time_it = local({ now <- NULL function(before, options) { if (before) { # record the current time before each chunk now <<- Sys.time() } else { # calculate the time difference after a chunk res <- difftime(Sys.time(), now) # return a character string to show the time paste("Time for this code chunk to run:", res) } } })) Then you can time a chunk with the chunk option time_it, e.g., {r, time_it = TRUE} Sys.sleep(2)  If you want to time all code chunks, you can certainly set the option globally: knitr::opts_chunk$set(time_it = TRUE).

In the above hook function, you can also output more information from the chunk options (i.e., the options argument of the function). For example, you may print out the chunk label in the returned value:

paste("Time for the chunk", options$label, "to run:", res) Or you may record the time without printing it out in the hook: all_times <- list() # store the time for each chunk knitr::knit_hooks$set(time_it = local({
now <- NULL
function(before, options) {
if (before) {
now <<- Sys.time()
} else {
res <- difftime(Sys.time(), now)
all_times[[options\$label]] <<- res
}
}
}))

Then you can access all the time information in the object all_times, which is a named list with the names being chunk labels, and element values being the execution time for each chunk.