knitr::opts_chunk$set(
  comment = "#>",
  collapse = TRUE,
  cache = TRUE, 
  fig.align = "center",
  fig.pos = "t"
)

Byte compiler

Byte compiler

Benchmarks

local(source("code/02-byte_f1.R", local = TRUE))

More info in the vignettes

vignette("slides_byte", package = "efficientTutorial")

Since it's now default behaviour, we'll move on

Byte compiler: the mean() function

getFunction("mean")

note the bytecode line

Byte compiler

Example: Bad mean

mean_r = function(x) {
  total = 0
  n = length(x)
  for (i in 1:n)
    total = total + x[i] / n
  total
}

Compiled version

library("compiler")
cmp_mean_r = cmpfun(mean_r)
cmp_mean_r  

Since 3.4.0 this is done automatically

Timings: don't rely on 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 

Benchmarks (R < 3.4.0)

# 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  

Benchmarks

local(source("code/02-byte_f1.R", local = TRUE))

Package authors

If you create a package, then you automatically compile the package on installation by adding

ByteCompile: true

to the DESCRIPTION file

Packages on CRAN

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

You will be compiled!

## Windows users need Rtools
install.packages("ggplot2", 
                 type = "source", 
                 INSTALL_opts = "--byte-compile") 


jr-packages/efficientTutorial documentation built on Feb. 16, 2020, 7:05 p.m.