Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopwatch function in R

Tags:

r

matlab

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

like image 559
wahalulu Avatar asked Sep 10 '25 05:09

wahalulu


2 Answers

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()

like image 182
Richie Cotton Avatar answered Sep 12 '25 19:09

Richie Cotton


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>
like image 21
rcs Avatar answered Sep 12 '25 19:09

rcs