Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing for chunks?

Tags:

r

knitr

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.

like image 885
Stephen Eglen Avatar asked Jul 06 '14 11:07

Stephen Eglen


People also ask

What does it mean to chunk your time?

Time chunking is the act of blocking off large chunks of time for one task instead of bouncing between different, smaller tasks.

What is an example of chunking?

The chunking definition is grouping related items together so that someone can remember them more easily. An example of chunking is grouping the everyday items someone needs to have in their pockets before leaving the house. This might include house keys, car keys, cell phone, and a wallet or purse.

What is the chunking strategy?

- Chunking is a procedure of breaking up reading material into manageable sections. Before reading a “chunk” students are given a statement of purpose, which guides them to look for something specific in the text. This process is repeated until students complete the passage.


1 Answers

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.

like image 101
Yihui Xie Avatar answered Oct 18 '22 13:10

Yihui Xie