A good option for you is the lineprof
package from Hadley Wickham. Since the package is not in CRAN, you have to install from GitHub using the package devtools
:
install.packages("devtools")
library(devtools)
install_github("hadley/lineprof")
library(lineprof)
This installation may take a while, especially if you need to download RTools (which is a set of programs needed to install a source package installed outside of R).
lineprof
makes profiling line by line of code. To use it, your function must be in a separate .R file, and be loaded using source()
:
Example.R file (I have modified your example to have a more useful output, the function does not work well with for
and it will not work for very fast operations):
exemplo = function(x){
res= 0
sapply(seq_along(x), function(i) {
res <- i + res
})
res_raiz = replicate(1000, sqrt(abs(res)))
return(res/res_raiz)
}
Finally, to do profiling, you can go to another file or the console:
source("exemplo.R")
lp <- lineprof(exemplo(rnorm(1e5)))
lp
# time alloc release dups ref
# 1 20.599 64.278 35.223 2 c("sapply", "lapply")
# 2 0.002 0.001 0.000 0 "sapply"
# 3 1.050 0.320 0.000 1 c("sapply", "simplify2array")
# 4 0.001 0.002 0.000 0 character(0)
# 5 0.192 0.656 0.000 2 c("replicate", "sapply")
# 6 0.001 0.001 0.000 0 "/"
# 7 0.012 0.001 0.000 0 character(0)
In addition to this simple view, you can also browse results using the shiny
:
shine(lp)
In this view, you can navigate the levels of functions to see what is slowest internally.
You can see more details about proofing and use of this function in Hadley website >.