Vectorization

system.time (
        {
        x.mx <- matrix (data = rand.nv, ncol = 2, nrow = len.n)
        x1.nv <- apply (x.mx, 1, sum)
        }
)

#   user  system elapsed 
#  0.878   0.012   0.885 

system.time (
        {
        x.mx <- matrix (data = rand.nv, ncol = 2, nrow = len.n)
        x2.nv <- numeric ()
        for (i in 1: 10^5)
                {x2.nv[i] <- sum (x.mx[i, ])}
        }
)

#   user  system elapsed 
# 20.527  44.616  64.834 
 
system.time (
        {
        x.mx <- matrix (data = rand.nv, ncol = 2, nrow = len.n)
        i.ls <- as.list (1: len.n)
        f.sum <- function (i.n, x.mx) {return (sum (x.mx[i.n, ]))}
        x3.nv <- sapply (i.ls, f.sum, x.mx)
        }
)

#   user  system elapsed 
#  0.573   0.014   0.584 

DanieleMerico/Code/Efficiency_Vectorization (last edited 2011-02-01 15:30:53 by DanieleMerico)

MoinMoin Appliance - Powered by TurnKey Linux