Here’s an improved system.time function for R
[This article was first published on "R-bloggers" via Tal Galili in Google Reader, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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 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() }
To leave a comment for the author, please follow the link and comment on their blog: "R-bloggers" via Tal Galili in Google Reader.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.