There are an array of approaches to measure function execution time in R (system.time(), microbenchmark(), proc.time(), profvis() etc) but they all involve wrapping these functions around your individual calls to time the process e.g.
system.time(a <- rnorm(10e7))
# user system elapsed
# 5.22 0.28 5.50
This is fine when you know you want to time something in advance but as is often the case, I run a piece of code and realise that it has been running for sometime and I have forgotten to wrap it in a timer function above.
Is there a way to automatically time all calls? A crude estimate is all I am looking for. I suspect this is challenging so even printing the local time after every call would be useful (e.g. call format(Sys.time(), "%H:%M:%S") after each call). Is there a way to set this at a top level perhaps via .rprofile?
There is a similar type of question asked here. Although the solution posed by @hadley is useful it requires all your calls to be in a script and source()ed. The question and answer are quite old now and I am wondering are there any newer clever ways to do this. I am using RStudio in case its of relevance here.
Thanks
EDIT
@Allan Cameron makes a good point. I wouldn't want the start time printed for every function but at the top level only. So, if I ran the following chunk, I would just want one time printed (current time when the overall chunk was started) and not a separate one for group_by, summarise, n() etc.
#library(dplyr)
starwars %>%
group_by(species) %>%
summarise(
n = n(),
mass = mean(mass, na.rm = TRUE)
) %>%
filter(
n > 1,
mass > 50
)
The following solution may work for you as long as you are using RStudio.
If you define the following function:
run_with_time <- function() {
cat(date())
rstudioapi::sendToConsole(
unclass(rstudioapi::getSourceEditorContext()$selection)[[1]]$text)
}
Then whenever you run this function, the current time will be printed and whatever code is selected in your code editor in the IDE will be run in the console.
However, it would be inconvenient to have to type in a function call to do this, so it would be better to create a keyboard shortcut that runs this function. That way, you select the code block you want to run, press the keyboard shortcut and you have a time-stamped code block running in your console.
Getting the function to be called from a keyboard shortcut in RStudio is a bit involved, but can be done, for example using the shrtcts package. A description of how to do this is available here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With