Search code examples
rr-markdownknitrbookdown

How to speed up bookdown generation?


I'm currently working on a book using bookdown. It uses some code snippets which take time to compile, execute and get output. I use the following commands to build HTML, PDF and EPUB files for the book:

Rscript -e "bookdown::render_book('index.Rmd', 'bookdown::gitbook')"
Rscript -e "bookdown::render_book('index.Rmd', 'bookdown::pdf_book')"
Rscript -e "bookdown::render_book('index.Rmd', 'bookdown::epub_book')"

So, every time the book files are generated the actual computation takes place increasing the overall generation time ×3.

Is there any way to produce some intermediate file on the first run and than use it to build HTML, PDF and EPUB outputs?


Solution

  • I managed to significantly reduce the regeneration time by adding the following snippet to my index.Rmd:

    ```{r include=FALSE}
    knitr::opts_chunk$set(cache = TRUE)
    ```
    

    Update:

    As Yuriy Barvinchenko and Yihui Xie both suggested, it's better to cache only time-consuming code chunks:

    ```{go time-sleep-demo cache = TRUE}
    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        fmt.Print("Hello ")
        time.Sleep(10 * time.Second)
        fmt.Println("world!")
    }
    ```