Here’s an improved system.time function for R

May 14, 2006

(This article was first published on User Primary » R, and kindly contributed to R-bloggers)

R’s current system.time function doesn’t name the vector of return values. Doing so makes it easier to understand the output. IMO, the current code has two uglies: it sets an on.exit hook and then calls on.exit() explicitly. It also computes the elapsed time twice (once for the stdout message and once for the return value). Another minor shortcoming is that when nested, only the outer call will print anything.

Anyhow, here’s an improved version that uses tryCatch instead of on.exit. One thing I wish was easier (maybe it is and I just don’t know) is reproducing the error message.

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
    loc.frame <- parent.frame()
    if (gcFirst)
    expr <- substitute(expr)
    time <- proc.time()
    show_time <- function() {
        t <- proc.time() - time
        names(t) <- nms
        cat("Timing stopped at:\n")
    tryCatch(eval(expr, envir = loc.frame),
             error=function(e) {
                 msg <- paste("Error in", deparse(conditionCall(e)),
                              ":", conditionMessage(e), "\n")

To leave a comment for the author, please follow the link and comment on their blog: User Primary » R. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...


Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)