Update:
As pointed out by @Dave2e, moving the start_time
statement (in code 2) out of the for
loop will make the running time comparable to code 1. Namely:
start_time <- Sys.time()
for (j in 1:1) {
n <- 100
result <- 1
for (i in 1:n) {
result <- result * i
}
result
## [1] 9.332622e+157
end_time <- Sys.time()
}
end_time - start_time
Does the for
loop really improve the performance or is it fake?
Original Post:
I have two pieces of codes as follows:
Code 1:
start_time <- Sys.time()
n <- 100
result <- 1
for (i in 1:n) {
result <- result * i
}
result
## [1] 9.332622e+157
end_time <- Sys.time()
end_time - start_time
Code 2:
for (j in 1:1) {
start_time <- Sys.time()
n <- 100
result <- 1
for (i in 1:n){
result <- result * i}
result
## [1] 9.332622e+157
end_time <- Sys.time()
}
end_time - start_time
I was expecting these two codes run similarly, but Code 2 constantly runs significantly faster than code 1. On my computer, code 1 takes about 10^-2 seconds, while code 2 takes about 5*10^-6 seconds. Any insight on how this could happen? If just adding for
loop to the entire codes can decrease program running time, I will use it on all my codes in the future.