Skip to content

Instantly share code, notes, and snippets.

@lgatto
Created March 5, 2011 13:44
Show Gist options
  • Save lgatto/856359 to your computer and use it in GitHub Desktop.
Save lgatto/856359 to your computer and use it in GitHub Desktop.
Comparing for, apply and vectorised functions
m <- matrix(runif(1e6),nrow=10000)
## append to result vector -- slow
res1 <- NULL
t1 <- system.time(for (i in 1:1000) res1[i] <- sum(m[i,]))
## initialise to full length -- fast
res2 <- numeric(1000)
t2 <- system.time(for (i in 1:1000) res2[i] <- sum(m[i,]))
## using apply -- slowest!
t3 <- system.time(res3 <- apply(m,1,sum))
## vectorised function -- fastest
t4 <- system.time(res4 <- rowSums(m))
cbind(t1,t2,t3,t4)
## t1 t2 t3 t4
## user.self 0.01 0.010 0.120 0.000
## sys.self 0.00 0.000 0.000 0.000
## elapsed 0.01 0.007 0.115 0.003
## user.child 0.00 0.000 0.000 0.000
## sys.child 0.00 0.000 0.000 0.000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment