Define a callback to run a command

I am trying to automatically execute all top level expressions. Task handlers are what you need, however, they are only called after the command completes, not before.

An alternative approach would be to change every top level expression that needs to be wrapped in system.time

, however I also don't know how to do this.

+3


source to share


3 answers


Two years late, but try this solution to automatically execute all commands:

proc <- function(...) {
    utime <- proc.time()[1]
    utime_diff <- utime-get0(".prev_time", envir=globalenv(), ifnotfound=0)
    options(prompt=paste0(utime_diff,"s> "))
    assign(".prev_time", utime, envir=globalenv())
    return(TRUE)
    }
ret <- addTaskCallback(proc)

      

The "user time" returned by proc.time does not increase when idle, so it calculates the time it takes to execute the command.

This gives you a pretty close measure, up to at least 10th of a second:



start_time <- proc.time()[1]

st_time <- system.time({for(x in 1:10000000) {
    log(x)
}})[1]

pt_time <- proc.time()[1] - start_time

print(paste("time using proc.time()", pt_time))
print(paste("time using syste.time()", st_time))

      

"using proc.time () 1.908"

"using syste.time () 1.884"

+2


source


For completeness, there is a function here that you can use as a task callback to automatically trigger a system notification for any top-level command that takes more than 5 seconds to complete.



# devtools::install_github("gaborcsardi/notifier")
notify_long_running <- function(second_cutoff = 5) {
  last <- proc.time()[1]
  function(expr, value, ok, visible) {
    duration <- proc.time()[1] - last
    if (duration > second_cutoff) {
      notifier::notify(msg = paste0(collapse = " ", deparse(expr)),
                       title = sprintf("Completed in %.02f (s)", duration))
    }
    last <<- proc.time()[1]
    TRUE
  }
}

addTaskCallback(notify_long_running())

      

+8


source


There is no real way to profile top-level commands, because R doesn't know what they are. How do you define them?

If system.time isn't granular enough for you (because it doesn't look at individual pieces of code), my suggestion would be to go backwards and use Rprof , which allows you to start and stop syncing expressions, and on exit ( summaryRprof()

) the breakdown by function call is displayed. Keep in mind that this is by function call, not by "top-level" function call: if you are looking specifically for R to compare everything you think of as a top-level function system.time

might really be your best bet

-2


source







All Articles