Skip to content
Prev 20625 / 63421 Next

Suggestion for system.time()

Fran?ois Pinard <pinard at iro.umontreal.ca> writes:
Here's a function you could try.  It names the result as you
suggested.  It also can be nested, which system.time cannot, because
it uses on.exit without specifying add=TRUE.

timeit <- function (expr, gcFirst = TRUE) 
{
    nms <- c("User", "System", "Elapsed", "Sub.User", "Sub.System")
    if (!exists("proc.time")) {
        ans <- rep(as.numeric(NA), 5)
        names(ans) <- nms
        return(ans)
    }
    loc.frame <- parent.frame()
    if (gcFirst) 
        gc(FALSE)
    expr <- substitute(expr)
    time <- proc.time()
    show_time <- function() {
        t <- proc.time() - time
        names(t) <- nms
        cat("Timing stopped at:\n")
        print(t)
        t 
    }
    tryCatch(eval(expr, envir = loc.frame),
             error=function(e) {
                 msg <- paste("Error in", deparse(conditionCall(e)),
                              ":", conditionMessage(e), "\n")
                 cat(msg)
             })
    show_time()
}


## Examples
Timing stopped at:
      User     System    Elapsed   Sub.User Sub.System 
     0.007      0.001      0.008      0.000      0.000
User     System    Elapsed   Sub.User Sub.System 
     0.007      0.001      0.008      0.000      0.000 

## Nested calls.  I dunno, could be useful in some debugging 
## situations *shrug*
Timing stopped at:
      User     System    Elapsed   Sub.User Sub.System 
     0.012      0.002      0.014      0.000      0.000 
Timing stopped at:
      User     System    Elapsed   Sub.User Sub.System 
     0.090      0.003      0.146      0.000      0.000
User     System    Elapsed   Sub.User Sub.System 
     0.090      0.003      0.146      0.000      0.000 


## With an error
Error in plot(foobarbaz) : object "foobarbaz" not found 
Timing stopped at:
      User     System    Elapsed   Sub.User Sub.System 
     0.002      0.000      0.038      0.000      0.000
User     System    Elapsed   Sub.User Sub.System 
     0.002      0.000      0.038      0.000      0.000