A good option for you is the package lineprof
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).
The lineprof
makes the Profiling line by line of code. To use it, its function must be in a separate. R file, and be loaded using source()
:
Example file. R (I modified your example to have a more useful output, the function does not work well with for
and also will not have result 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 make the Profiling, you can go in another file or 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 preview, you can also browse the results using the package shiny
:
shine(lp)
In this view you can navigate the levels of the functions to see internally what is slower.
You can see more details about proofing and the use of this function in hadley’s website.
Can you put an example of a function you want to evaluate? The most "crude" method is to simply save the
Sys.time()
before and after, but as you have seen there are more robust solutions.– Molx
Wagner, I appreciate you flagging my answer as correct, but I suggest you switch to Carlos'. The package I mentioned is no longer under development and this response may become invalid at any time, the answer.
– Molx
Jeez, I made a mistake. I thank you for the numerous help and sincerity. You are saving my master’s degree, hehehehe.
– Wagner Jorge