开发者

Stopwatch function in R

Is there an R time开发者_如何学JAVAr or stopwatch function similar to MATLAB's tic/toc?


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


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>


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.


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


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


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


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 


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜