1

I guess I have a simple and straightforward question.

I am running a script and for each function I want to time the runtime of the function. I suppose there is a function to time my function. Can anybody help me here?

I have been searching but keep finding functions for time series and time intervals. I am not searching that.

Zuenie
  • 963
  • 2
  • 11
  • 30
  • `system.time` could be a solution. To find, alternative solutions, use the key word "CPU" : `RSiteSearch("CPU")`. – Vincent Guillemot Aug 06 '14 at 09:56
  • The `tictoc` package is another option. It enables you to time a whole script by starting it with `tic()`, running the rest of your code, and then ending it with `toc()`. You can also nest several timers and give them names for clarity: `tic("everything"); tic("data"); [import data]; toc(); tic("model"); [run a model]; toc(); toc()`, which would give you a timer for the whole thing ("everything"), and timers for the data importation ("data") and modeling ("model"). – coip Aug 23 '21 at 22:53

1 Answers1

3

As the others in the comments mentioned before, the simplest way is with system.time. Here's an example code from the system.time manual page

require(stats)
system.time(for(i in 1:100) mad(runif(1000)))

## Not run: 
exT <- function(n = 10000) {
  # Purpose: Test if system.time works ok;   n: loop size
  system.time(for(i in 1:n) x <- mean(rt(1000, df = 4)))
}

#-- Try to interrupt one of the following (using Ctrl-C / Escape):
exT()                 #- about 4 secs on a

2.5GHz Xeon
system.time(exT())    #~ +/- same

On my machine, once the function exT() is called, this is my output:

    user  system elapsed 
   2.916   0.004   2.925

And for the function system.time(exT()) I get the following output:

   user  system elapsed 
  3.004   0.016   3.026 

This means that for the first case the elapsed time is 2.925 seconds and 3.026 for the second.

However, if you want to perform benchmark tests, you should use the package rbenchmark (go here). This is a library which consists of one function:

The library consists of just one function, benchmark, which is a simple wrapper around system.time.

On the link I've provided, you can see more examples of how to use this package. There are 4 examples there, which are pretty good.

Belphegor
  • 4,456
  • 11
  • 34
  • 59