Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201945

Why is the computation is faster with a loop?

$
0
0

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.


Viewing all articles
Browse latest Browse all 201945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>