在R中是否有衡量函数执行时间的标准化方法?

显然我可以用系统。时间,然后取它们的差异,但我想知道是否有一些标准化的方法或功能(不想发明轮子)。


我似乎记得我曾经用过如下的东西:

somesysfunction("myfunction(with,arguments)")
> Start time : 2001-01-01 00:00:00  # output of somesysfunction
> "Result" "of" "myfunction"        # output of myfunction
> End time : 2001-01-01 00:00:10    # output of somesysfunction
> Total Execution time : 10 seconds # output of somesysfunction

当前回答

编译以上所有的答案,我想到使用这些简化的tic toc函数

tic <- function(){ start.time <<- Sys.time() }
toc <- function(){ round(Sys.time() - start.time) }

用作:

tic()
Sys.sleep(3)
toc()

哪些印刷品:

时间差3秒

其他回答

正如Andrie所说,system.time()工作正常。对于短函数,我更喜欢在其中放入replication ():

system.time( replicate(10000, myfunction(with,arguments) ) )

microbenchmark是一个轻量级(约50kB)包,或多或少是R中对多个表达式和函数进行基准测试的标准方法:

microbenchmark(myfunction(with,arguments))

例如:

> microbenchmark::microbenchmark(log10(5), log(5)/log(10), times = 10000)
Unit: nanoseconds
           expr min lq    mean median uq   max neval cld
       log10(5)   0  0 25.5738      0  1 10265 10000   a
 log(5)/log(10)   0  0 28.1838      0  1 10265 10000

在这里,两个表达式都被计算了10000次,平均执行时间约为25-30纳秒。

您可以使用Sys.time()。但是,当您在表格或csv文件中记录时差时,不能简单地使用end - start。相反,你应该定义这个单位:

f_name <- function (args*){
start <- Sys.time()
""" You codes here """
end <- Sys.time()
total_time <- as.numeric (end - start, units = "mins") # or secs ... 
}

然后你可以使用total_time,它有一个合适的格式。

虽然其他解决方案对于单个函数也很有用,但我推荐使用下面的代码段,因为它更通用、更有效:

Rprof(tf <- "log.log", memory.profiling = TRUE)
# the code you want to profile must be in between
Rprof (NULL) ; print(summaryRprof(tf))

内置函数system.time()将执行此操作。

使用like: system。Time (result <- myfunction(with, arguments))