Taotao Tan
Taotao Tan

Reputation: 283

Missing time elapsed within a loop

I noticed that the time elapsed within a loop doesn’t sum up to the total amount of time elapsed for the function. For instance

# run matrix multiplication 100 times
n = 5000
randommat = matrix(runif(n*n), nrow = n)
randomvec = runif(n)


RunSimu <- function(){
  timetot = c()
  for (i in 1:100){
    timetot[i] = system.time(randommat %*% randomvec)[3]
  }
  return(timetot)
}

# count the total time of running the function
system.time(timetot<- RunSimu()) # approx 7s

# sum up time elapsed for each loop
sum(timetot) # approx 1.5s

Intuitively, the totals amount of time elapsed for the function should be 100 * time elapsed for each iteration. But they seem to be quite different. Where is the missing time?

Upvotes: 0

Views: 45

Answers (1)

minem
minem

Reputation: 3650

system.time by default calls gc every time, see ?system.time. We can turn that off:

RunSimu2 <- function(){
  timetot = vector('numeric', 100)
  for (i in 1:100) {
    timetot[i] = system.time(randommat %*% randomvec, gcFirst = F)[3]
  }
  return(timetot)
}
system.time(timetot2<- RunSimu2()) # 2.69 
sum(timetot2) # 2.69

or with proc.time:

r3 <- function(){
  timetot = vector('numeric', 100)
  for (i in 1:100) {
    t1 <- proc.time()
    a = randommat %*% randomvec
    t2 <- proc.time()
    timetot[i] = (t2-t1)[3]
  }
  return(timetot)
}
system.time(t3 <- r3()) # 2.70 
sum(t3) # 2.7

Upvotes: 1

Related Questions