简体   繁体   中英

Hook to time knitr chunks

I would like to time knitr chunks and record how long it took to render them using comments in LaTeX output.

I've tried the following hook:

 now = Sys.time()
 knit_hooks$set(timeit = function(before) {
     if (before) { now <<- Sys.time() }
     else {
         paste("%", sprintf("Chunk rendering time: %s seconds.\n", round(Sys.time() - now, digits = 3))) 
     }
 })

And it does produce the correct comment with timing but the problem is that it's wrapped in kframe which results in ugly gaps in the LaTeX output:

\begin{kframe}

% Chunk rendering time: 12.786 seconds.

\end{kframe}

Is there a way to produce unwrapped comments?

Try this:

local({
  now = Sys.time()
  knit_hooks$set(timeit = function(before) {
    if (before) {
      now <<- Sys.time()
    } else {
      x = round(Sys.time() - now, digits = 3)
      x = sprintf("%% Chunk rendering time: %s seconds.", x)
      paste('\\end{kframe}\n', x, '\n\\begin{kframe}')
    }
  })
})

It is a hack, though. Basically you escape the LaTeX comment from the kframe environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM