r - Faster to run two loops or one loop -


in general, if number of iterations of 2 loops same, faster run 2 loops or combine 2 loops 1 loop?

i have imagined running 1 loop should faster, when wrote test code, not case. can explain why is?

here code example in r

tic <- function(gcfirst = true, type=c("elapsed", "user.self", "sys.self")) {    type <- match.arg(type)    assign(".type", type, envir=baseenv())    if(gcfirst) gc(false)    tic <- proc.time()[type]             assign(".tic", tic, envir=baseenv())    invisible(tic) }  toc <- function() {    type <- get(".type", envir=baseenv())    toc <- proc.time()[type]    tic <- get(".tic", envir=baseenv())    print(toc - tic)    invisible(toc) }  > tic()  > for(i in 1:10000){ + x = rnorm(1000) + y = rnorm(1000) + } > toc() elapsed     1.78  >  >  > tic()  > for(i in 1:10000){ + x = rnorm(1000) + } > for(i in 1:10000){ + y = rnorm(1000) + } > toc() elapsed     1.78  

so see, took 1 loop 1.78 seconds , took 2 loops 1.78 seconds well.

in 2 loop example, second loop runs 1000. accounts difference. in general case, it's complicated answer because depends on locality, cache size, , operations doing can pipelined. difference negligible , relevant in performance critical applications. should prioritize clarity of code.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

android - Keyboard hides my half of edit-text and button below it even in scroll view -