Fun: tic and toc in R

To measure how much time a computation takes in MATLAB, we can wrap it into tic and toc.

tic
% do something
toc

In R, we would use system.time; there exist also several packages that offer convenient functions to profile code.

But we can also make R behave like MATLAB. The following print methods use the code from R's system.time function.

tic <- 1
class(tic) <- "tic"

toc <- 1
class(toc) <- "toc"

print.tic <- function(x,...) {
    if (!exists("proc.time"))
        stop("cannot measure time")
    gc(FALSE)
    assign(".temp.tictime", proc.time(), envir = .GlobalEnv)
}

print.toc <- function(x,...) {
    if (!exists(".temp.tictime", envir = .GlobalEnv))
        stop("Did you tic?")
    time <- get(".temp.tictime", envir = .GlobalEnv)
    rm(".temp.tictime", envir = .GlobalEnv)
    print(res <- structure(proc.time() - time,
                           class = "proc_time"), ...)
    invisible(res)
}

The example

tic
Sys.sleep(2)
toc

should result in something like this:

   user  system elapsed
      0       0       2

(the tangled R-code)

return to main page...

return to R page...