Created
May 9, 2017 16:57
-
-
Save wjhopper/3650f2d478fa268c47a04298bc5fe7e8 to your computer and use it in GitHub Desktop.
apply vs for-loop benchmark in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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