A Profiling Example

f1 <- myColumnSumsLoop <- function(x) {
    nrow <- nrow(x)
    ncol <- ncol(x)
    sums <- rep(0, ncol)
    for (i in 1:ncol) for (j in 1:nrow) sums[i] = sums[i] + x[j, i]
    return(sums)
}

f2 <- myColumnSumsApply <- function(x) {
    return(apply(x, 2, sum))
}

f3 <- myColumnSumsFunction <- function(x) {
    return(colSums(x))
}
set.seed(12345)
x <- matrix(1, 10000, 100)
Rprof(file = "myProfile.txt")
for (i in 1:100) {
    f1(x)
    f2(x)
    f3(x)
}
Rprof(NULL)
summaryRprof("myProfile.txt")
## $by.self
##                 self.time self.pct total.time total.pct
## "f1"               113.80    96.92     116.16     98.93
## "+"                  1.20     1.02       1.20      1.02
## ":"                  1.16     0.99       1.16      0.99
## "apply"              0.74     0.63       1.20      1.02
## "aperm.default"      0.44     0.37       0.44      0.37
## "colSums"            0.06     0.05       0.06      0.05
## "aperm"              0.02     0.02       0.46      0.39
## 
## $by.total
##                       total.time total.pct self.time self.pct
## "block_exec"              117.42    100.00      0.00     0.00
## "call_block"              117.42    100.00      0.00     0.00
## "doTryCatch"              117.42    100.00      0.00     0.00
## "eval"                    117.42    100.00      0.00     0.00
## "evaluate_call"           117.42    100.00      0.00     0.00
## "evaluate"                117.42    100.00      0.00     0.00
## "handle"                  117.42    100.00      0.00     0.00
## "in_dir"                  117.42    100.00      0.00     0.00
## "knit"                    117.42    100.00      0.00     0.00
## "process_file"            117.42    100.00      0.00     0.00
## "process_group.block"     117.42    100.00      0.00     0.00
## "process_group"           117.42    100.00      0.00     0.00
## "try"                     117.42    100.00      0.00     0.00
## "tryCatch"                117.42    100.00      0.00     0.00
## "tryCatchList"            117.42    100.00      0.00     0.00
## "tryCatchOne"             117.42    100.00      0.00     0.00
## "withCallingHandlers"     117.42    100.00      0.00     0.00
## "withVisible"             117.42    100.00      0.00     0.00
## "f1"                      116.16     98.93    113.80    96.92
## "+"                         1.20      1.02      1.20     1.02
## "apply"                     1.20      1.02      0.74     0.63
## "f2"                        1.20      1.02      0.00     0.00
## ":"                         1.16      0.99      1.16     0.99
## "aperm"                     0.46      0.39      0.02     0.02
## "aperm.default"             0.44      0.37      0.44     0.37
## "colSums"                   0.06      0.05      0.06     0.05
## "f3"                        0.06      0.05      0.00     0.00
## 
## $sample.interval
## [1] 0.02
## 
## $sampling.time
## [1] 117.4