Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook to time knitr chunks

Tags:

r

latex

knitr

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?

like image 339
god Avatar asked May 29 '15 12:05

god


People also ask

What does knitr :: Opts_chunk set echo true mean?

The first code chunk: ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` is used to specify any global settings to be applied to the R Markdown script. The example sets all code chunks as “echo=TRUE”, meaning they will be included in the final rendered version.

How do I cache a chunk in R?

Caching a code chunk in R Markdown R Markdown has a built-in caching feature that can be enabled by setting cache=TRUE in the chunk's header. The second time the chunk is run, both the visual output and any objects created are loaded from disk.

What is the purpose of knitr?

knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.


1 Answers

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.

like image 88
Yihui Xie Avatar answered Sep 22 '22 08:09

Yihui Xie