Skip to content

Instantly share code, notes, and snippets.

@wjhopper
Created May 9, 2017 16:57
Show Gist options
  • Save wjhopper/3650f2d478fa268c47a04298bc5fe7e8 to your computer and use it in GitHub Desktop.
Save wjhopper/3650f2d478fa268c47a04298bc5fe7e8 to your computer and use it in GitHub Desktop.
apply vs for-loop benchmark in R
#The task: sum 1000 different 10x10 matrices stored in a list
matrices <- vector(mode="list", length=1000)
for (i in seq_along(matrices)) {
matrices[[i]] <- matrix(rnorm(1000), 10, 10)
}
f1 <- function () {
S <- matrix(0, 10, 10)
for (M in matrices) {
S <- S + M
}
}
f2 <- function() {
S <- apply(array(unlist(matrices),
dim = c(10, 10, 1000)),
1:2, sum)
}
library(microbenchmark)
microbenchmark(for_loop = f1(), apply = f2())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment