Timing for chunks?

后端 未结 1 614
一整个雨季
一整个雨季 2021-01-02 06:21

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

相关标签:
1条回答
  • 2021-01-02 06:38

    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.

    0 讨论(0)
提交回复
热议问题