Loop
a<-runif(1000000, 1, 100)
b<-runif(1000000, 1, 100)
c.loop<-0
c.loop.time<-c(rep(0,10))
#loop method
for(i in 1:10){
start.time <- Sys.time()
for(j in 1:1000000){
c.loop<-c.loop+a[j]*b[j]
}
c.loop.time[i]<-c(as.double( Sys.time() - start.time))
}
#the 10 execution time
c.loop.time
## [1] 1.0402119 1.0251732 0.9971929 1.0236001 1.0224719 1.0570061 1.0201309
## [8] 1.0530169 1.0098500 1.0141699
print(paste0("The loop execution taks on average ",round(mean(c.loop.time),5) ," seconds."))
## [1] "The loop execution taks on average 1.02628 seconds."
Vectorization
c.vector<-0
c.vector.time<-c(rep(0,10))
#vectorization method
for(i in 1:10){
start.time <- Sys.time()
c.vector<-sum(a*b)
c.vector.time[i]<-c(as.double( Sys.time() - start.time))
}
c.vector.time
## [1] 0.004498959 0.007035017 0.007002115 0.041497946 0.004499912
## [6] 0.005006075 0.009495020 0.004502058 0.004501820 0.009001017
print(paste0("The vectorization execution takes on average ",round(mean(c.vector.time),5) ," seconds."))
## [1] "The vectorization execution takes on average 0.0097 seconds."