Timing for chunks?
knitr, r
Solution
You can define a chunk hook function to do this. Here is a quick example:
{r setup, include=FALSE} knitr::knit_hooks$set(timeit = local({ now = NULL function(before, options) { if (before) { now <<- Sys.time() } else { res = difftime(Sys.time(), now) now <<- NULL # use options$label if you want the chunk label as well paste('Time for this code chunk:', as.character(res)) } }}) )
Test it:
{r test-a, timeit = TRUE} Sys.sleep(2)
`
Depending on the document format that you work with, you may want to format the character string returned by the hook. Character results returned from the chunk hooks are combined with the original output, and other types of output are ignored.
Problem
Is there any way to report how much time it takes to compute each chunk? I am working on creating a document from some large scripts, and it would be nice to know where the time is taken. I do use the caching feature, so of course once objects are cached, it is not too slow to work with the document, but I'd like to isolate the slow chunks to see how I can stop them being recomputed unless absolutely needed. One thought was e.g. to wrap each chunk in system.time() and report the system.time underneath each chunk output, or in the margin... Thanks again Yihui for such excellent software.