2

I need to compare two functions in terms of elapsed time. At the moment I am using the following code:

system.time(f1())
system.time(f2())

And if I want to run the same functions multiple times I use:

system.time(replicate(10, f1()))
system.time(replicate(10, f2()))

The information that I get from system.time is user, system and elapsed time.

The point is that I would know, if I replicate the function, also the min and max elapsed time of the single call.

How can I do?

Nick
  • 10,309
  • 21
  • 97
  • 201

1 Answers1

2

If you are not constrained by using only base packages, I would suggest using microbenchmark package.

> f1 <- function() 1
> f2 <- function() 2
> microbenchmark::microbenchmark(f1(), f2(), times = 10)
Unit: nanoseconds
 expr min  lq  mean median  uq  max neval cld
 f1() 134 195 896.7    309 360 6418    10   a
 f2() 133 138 305.3    189 230 1320    10   a

However, if you still want to use system.time, just move replicate outside of system.time call. For example,

> f1 <- function() sapply(1:100000, identity)
> times <- replicate(10, system.time(f1())[3])
> min(times)
[1] 0.051
> max(times)
[1] 0.057
romants
  • 3,660
  • 1
  • 21
  • 33