2

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

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

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

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

我从中获得的信息system.time是用户、系统和经过的时间。

关键是,如果我复制该函数,我会知道单次调用的最小和最大经过时间。

我能怎么做?

4

1 回答 1

2

如果您不受仅使用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
于 2015-12-09T21:19:23.007 回答