[R] decreasing performance of for() loop

bogdan romocea br44114 at gmail.com
Mon Oct 10 16:40:27 CEST 2005


Nevermind, I found the fix. Declaring the length for out eliminates
the performance decrease,
   out <- vector(mode="numeric",length=length(test))


On 10/10/05, bogdan romocea <br44114 at gmail.com> wrote:
> Dear useRs,
>
> I'm wondering why the for() loop below runs slower as it progresses.
> On a Win XP box, the iterations at the beginning run much faster than
> those at the end:
> 1%, iteration 2000, 10:10:16
> 2%, iteration 4000, 10:10:17
> 3%, iteration 6000, 10:10:17
> 98%, iteration 196000, 10:24:04
> 99%, iteration 198000, 10:24:24
> 100%, iteration 200000, 10:24:38
>
> Is there something that can be done about this?  Would such a loop run
> faster in C/C++/Fortran?
>
> Thank you,
> b.
>
> #---sample code
> loop.progress <- function(loop,iterations,steps,toprint=NULL)
> {
> marks <- c(1,floor(iterations/steps)*(1:steps))
> if (loop %in% marks) {
>         if (is.null(toprint)) prt <- loop else prt <- toprint
>         cat(paste(round((which(marks == loop)-1)*(100/steps),0),"%, iteration ",
>                 prt,", ",format(Sys.time(),"%H:%M:%S"),sep=""),"\n")
>         }
> }
> #---loop that runs slower and slower
> test <- runif(200000)
> out <- vector(mode="numeric")
> lg <- 30
> for (i in (lg+1):length(test))
>         {
>         loop.progress(i,length(test),100)
>         out[i] <- sum(test[(i-lg):i])
>         }
>




More information about the R-help mailing list