Last active
December 14, 2015 20:59
-
-
Save emhart/5147602 to your computer and use it in GitHub Desktop.
timing in loops vs apply functions...
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
library(ggplot2) | |
# n is the number of iterations for the test | |
# j is the number of matrices to create | |
# m is the size of the square matrix to solve | |
loops <- function(n,j,m){ | |
for(i in 1:n){ | |
mylist <- list() | |
for(x in 1:j){mylist[[x]]<- matrix(rnorm(m^2),nrow=m,ncol=m)} | |
for(x in 1:j) {z <- solve(mylist[[x]])} | |
} | |
} | |
applies <- function(n,j,m){ | |
for(i in 1:n){ | |
mylist <- list() | |
for(x in 1:j){mylist[[x]]<- matrix(rnorm(m^2),nrow=m,ncol=m)} | |
out <- lapply(mylist,solve) | |
} | |
} | |
# Test with increasing matrix size from 2 to 100 | |
# This may take some time | |
loop_time_mz <- 0 | |
apply_time_mz <- 0 | |
for(i in 2:100){ | |
loop_time_mz <- c(loop_time_mz,system.time(loops(100,10,i), gcFirst = TRUE)[3]) | |
apply_time_mz <- c(apply_time_mz,system.time(applies(100,10,i), gcFirst = TRUE)[3]) | |
cat(i,"\n") | |
} | |
# test with increasing number of matrices, but a fixed matrix size | |
loop_time_nm <- 0 | |
apply_time_nm <- 0 | |
for(i in 2:100){ | |
loop_time_nm<- c(loop_time_nm,system.time(loops(100,i,10), gcFirst = TRUE)[3]) | |
apply_time_nm <- c(apply_time_nm,system.time(applies(100,i,10), gcFirst = TRUE)[3]) | |
cat(i,"\n") | |
} | |
time_df <- data.frame(cbind(rep(1:100,4),c(loop_time_mz,apply_time_mz,loop_time_nm,apply_time_nm))) | |
time_df$fxn <- c(rep("Loops",100),rep("Apply",100),rep("Loops",100),rep("Apply",100)) | |
time_df$type <- c(rep("Increasing matrix size",200),rep("Increasing number of matrices",200)) | |
names(time_df) <- c("size","time","Function","type") | |
ggplot(time_df,aes(x=size,y=time,group=Function,colour=Function))+geom_path()+facet_grid(type~.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment