Stopwatch function in R

前端 未结 10 1971
后悔当初
后悔当初 2020-12-08 07:27

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

相关标签:
10条回答
  • 2020-12-08 08:05

    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
    
    0 讨论(0)
  • 2020-12-08 08:09

    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()
    
    0 讨论(0)
  • 2020-12-08 08:23

    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

    0 讨论(0)
  • 2020-12-08 08:24

    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 
    
    0 讨论(0)
提交回复
热议问题