knitr::opts_chunk$set( comment = "#>", collapse = TRUE, cache = TRUE, fig.align = "center", fig.pos = "t" )
The compiler package has been part of R since version 2.13.0
Since R 2.14.0, all of the standard functions and packages in R will be pre-compiled into byte-code
Since R 3.4.0 JIT compilation has been enabled
Since R 3.5.0 all packages are now byte compiled
local(source("code/02-byte_f1.R", local = TRUE))
vignette("slides_byte", package = "efficientTutorial")
Since it's now default behaviour, we'll move on
getFunction("mean")
note the bytecode
line
mean_r = function(x) { total = 0 n = length(x) for (i in 1:n) total = total + x[i] / n total }
library("compiler") cmp_mean_r = cmpfun(mean_r) cmp_mean_r
n=1
x = rnorm(1e7) system.time(y <- mean_r(x)) # user system elapsed # 1.692 0.040 0.583 system.time(y <- mean_r(x)) # user system elapsed # 0.572 0.000 0.575
# Generate some data x = rnorm(1000) microbenchmark::microbenchmark(times = 10, unit = "ms", # milliseconds mean_r(x), cmp_mean_r(x), mean(x)) #> Unit: milliseconds #> expr min lq mean median uq max neval cld #> mean_r(x) 0.358 0.361 0.370 0.363 0.367 0.43 10 c #> cmp_mean_r(x) 0.050 0.051 0.052 0.051 0.051 0.07 10 b #> mean(x) 0.005 0.005 0.008 0.007 0.008 0.03 10 a
local(source("code/02-byte_f1.R", local = TRUE))
If you create a package, then you automatically compile the package on installation by adding
ByteCompile: true
to the DESCRIPTION file
Most R packages installed using install.packages()
are not compiled
byte = tools::CRAN_package_db()$ByteCompile sum(!is.na(byte)) / length(byte) * 100 # [1] 3.291
R_COMPILE_PKGS
R_COMPILE_PKGS=3
to ~/.Renviron
## Windows users need Rtools install.packages("ggplot2", type = "source", INSTALL_opts = "--byte-compile")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.