Is there an R timer or stopwatch function similar to MATLAB\'s tic/toc?
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
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()
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
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