R 中经过的时间 - 最小值、最大值

Elapsed time in R - min, max

我需要根据运行时间比较两个函数。目前我正在使用以下代码:

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

如果我想 运行 多次使用相同的功能,我会使用:

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

我从system.time得到的信息是用户、系统和运行时间。

要点是,如果我复制该函数,我还会知道单次调用的最短和最长耗时。

我该怎么办?

如果您不受限于仅使用 base 包,我建议您使用 microbenchmark 包。

> 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

但是,如果您仍想使用 system.time,只需将 replicate 移到 system.time 调用之外。例如,

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