25

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

1
  • for what it's worth, googling [r] tic toc now (Feb 2013) gives lots of answers; don't know if it did back in Nov 2011 or not ... Commented Feb 19, 2013 at 19:23

10 Answers 10

39

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

Sign up to request clarification or add additional context in comments.

Comments

14

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>

Comments

9

A very simple equivalence with tic and toc that you could have:

tic=proc.time()[3]

...code...

toc=proc.time()[3] - tic

Where the [3] is because we are interested in the third element in the vector returned by proc.time(), which is elapsed time.

Comments

8

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

Comments

7

A Closure Approach

A very clean and simple way to do this is by using a closure (which just means having a function within a function):

tic <- function () { 
    now <- proc.time()
    function () { 
        proc.time() - now 
    }
}

You start the timer like so:

toc <- tic()

And then you get the time back like this:

toc()

Which outputs a named vector that gets printed like so:

 user  system elapsed 
0.008   0.004   2.055 

Even with the simplicity of this version you also get all the functionality of the Matlab and Richie Cotton's versions plus the added feature of being able to run multiple timers:

toc1 <- tic()
toc2 <- tic()

Comments

4

There is a relatively new package tictoc that replicates the features exactly as you would use them in Matlab.

http://cran.r-project.org/web/packages/tictoc/index.html

## Basic use case
tic()
print("Do something...")
Sys.sleep(1)
toc()
# 1.034 sec elapsed

Comments

2

As of the date 2015-03-25, and possibly earlier, the pracma package contains the functions tic() and toc().

Example:

> library(pracma)
> tic()
> for(i in 1:10000) mad(runif(10000))    # kill time
> toc()
elapsed time is 18.610000 seconds 

Comments

2

No, but here is a one line solution.

time.it<-function(f) { a<-proc.time(); out<-f(); print(proc.time()-a); out }

And an example for usage:

result<-time.it(function(){ A<-matrix(runif(5000^2),nrow=5000); b<-runif(5000); solve(A,b) } )
user  system elapsed 
12.788  12.268   8.623 

Otherwise, microbenchmark is my favorite in terms of packages.

Comments

0

Just for completeness: you can actually 'simulate' tic and toc in R, so that you can write

tic
## do something
toc

without parentheses. The trick is to abuse the print function, as demonstrated in Fun: tic and toc in R:

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

So typing

tic
Sys.sleep(2)
toc

should results in something like this:

   user  system elapsed 
  0.000   0.000   2.002 

As I said, it's a trick; system.time, Rprof and packages such as rbenchmark are the way to measure computing time in R.

1 Comment

Links to external resources are encouraged. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline.
0
install.packages("tictoc")
library(tictoc)
# Timing nested code. 
# The string provided in the call to tic() becomes a prefix to the output of toc()
tic("outer")
    Sys.sleep(1)
    tic("middle")
        Sys.sleep(2)
        tic("inner")
            Sys.sleep(3)
        toc() # inner
# inner: 3.004 sec elapsed
    toc() # middle
# middle: 5.008 sec elapsed
toc() # outer
# outer: 6.016 sec elapsed

The tictoc package implements the functionality described by previous answers - thank you for inspiration! The package also adds nested timing, collecting the timings in user-defined variables, custom messages and callbacks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.