Skip to content
Prev 305678 / 398506 Next

Possible Improvement of the R code

Unlike C or C++, subscripting vector or matrix is not almost free.
Also, subscripting a matrix tends to make more time than subscripting a
vector so it can help to pull out the previous row of params once
per iteration, use vector subscripting on the that row to build the new
row, and then insert the new row back into params with one matrix
subscripting call:
f5 <- function(param) {
    for(i in 2:11) {
        # do matrix subscripting only twice per iteration
        prev <- param[i-1, ]
        param[i,] <- c(
            prev[3] + prev[4]/2,
            prev[4]/2 + prev[5],
            prev[1] * (prev[3] + prev[4]/2),
            prev[1] * (prev[4]/2 + prev[5]) + prev[2] * (prev[3] + prev[4]/2),
            prev[2] * (prev[4]/2 + prev[5]))
    }
    param
}
You can also do as much as possible to not repeat any subscripting or
sums:
f6 <- function(param) {
    for(i in 2:11) {
        # do any subscripting only twice/iteration and
        # repeated sums only once/iteration.
        prev <- param[i-1, ]
        p1 <- prev[1]
        p2 <- prev[2]
        p42 <- prev[4]/2
        p342 <- prev[3] + p42
        p425 <- p42 + prev[5]
        param[i,] <- c(
            p342,
            p425,
            p1 * p342,
            p1 * p425 + p2 * p342,
            p2 * p425)
    }
    param
}

I was curious about how much the compiler package could replace hand-optimization
so I timed these with and without compiling.  (f1 and f3 are Berend's f1 and f3; I renamed
his f2 and f4 to f1c and f3c to indicate they were the compiled versions.)
f1  f1c   f3  f3c   f5  f5c   f6 f6c
user.self 5.03 2.82 3.74 1.89 2.73 1.78 1.54 0.9
sys.self  0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
elapsed   5.03 2.83 3.75 1.90 2.76 1.77 1.54 0.9
raw compiled
f1 5.03     2.82
f3 3.74     1.89
f5 2.73     1.78
f6 1.54     0.90
It looks like both hand- and machine-optimization help quite a bit here.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com