Is there an R timer or stopwatch function similar to MATLAB's tic/toc?
10 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()
Comments
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
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
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
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
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
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
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
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.
[r] tic tocnow (Feb 2013) gives lots of answers; don't know if it did back in Nov 2011 or not ...