在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

当前回答

另一种可能的方法是使用Sys.time():

start.time <- Sys.time()
...Relevent codes...
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

与上面的答案相比,这不是最优雅的方法,但绝对是一种方法。

其他回答

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

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

另一种可能的方法是使用Sys.time():

start.time <- Sys.time()
...Relevent codes...
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

与上面的答案相比,这不是最优雅的方法,但绝对是一种方法。

您可以使用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,它有一个合适的格式。

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

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

还有proc.time()

你可以用和Sys一样的方法使用。Time但是它给你的结果和system。Time类似。

ptm <- proc.time()
#your function here
proc.time() - ptm

主要区别使用

system.time({ #your function here })

proc.time()方法仍然执行你的函数,而不是仅仅测量时间… 顺便说一下,我喜欢使用系统。时间{}在里面,所以你可以把一组东西…