tags:

views:

372

answers:

3

Is there an R timer or stopwatch function similar to MATLAB's tic/toc?

+5  A: 

Direct equivalents of tic and toc do not exist.

Please see help(system.time) as well as the R Extensions manual about profiling. Discussions of profiling and profiling tools is also in the 'Intro to HPC with R' slides referenced on the High Performance Computing with R taskview

Dirk Eddelbuettel
+10  A: 

There are plenty of profiling tools in R, as Dirk mentioned. If you want the simplicity of tic/toc, then you can do it in R too.

EDIT: I've cannibalised the garbage collection functionality from the MATLAB package, and tic now lets you choose whether you are interested in total elapsed time or just the user time.

tic <- function(gcFirst = TRUE, type=c("elapsed", "user.self", "sys.self"))
{
   type <- match.arg(type)
   assign(".type", type, envir=baseenv())
   if(gcFirst) gc(FALSE)
   tic <- proc.time()[type]         
   assign(".tic", tic, envir=baseenv())
   invisible(tic)
}

toc <- function()
{
   type <- get(".type", envir=baseenv())
   toc <- proc.time()[type]
   tic <- get(".tic", envir=baseenv())
   print(toc - tic)
   invisible(toc)
}

Usage is, e.g., tic(); invisible(qr(matrix(runif(1e6), nrow=1e3))); toc()

Richie Cotton
+7  A: 

There is a MATLAB emulation package matlab on CRAN. It has implementations of tic and toc (but they look very similar to the functions in Richie Cottons answer; "elapsed" is used instead of "user.self" in proc.time())

> tic
function (gcFirst = FALSE) 
{
    if (gcFirst == TRUE) {
        gc(verbose = FALSE)
    }
    assign("savedTime", proc.time()[3], envir = .MatlabNamespaceEnv)
    invisible()
}
<environment: namespace:matlab>
> toc
function (echo = TRUE) 
{
    prevTime <- get("savedTime", envir = .MatlabNamespaceEnv)
    diffTimeSecs <- proc.time()[3] - prevTime
    if (echo) {
        cat(sprintf("elapsed time is %f seconds", diffTimeSecs), 
            "\n")
        return(invisible())
    }
    else {
        return(diffTimeSecs)
    }
}
<environment: namespace:matlab>
rcs

related questions