在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秒

其他回答

library(rbenchmark)

sleep_func <- function() { Sys.sleep(0.5) }

benchmark(sleep_func())

out:

 test replications elapsed relative user.self sys.self user.child sys.child

1 sleep_func()          100   50.08        1      0.02        0         NA        NA

有几个答案提到取两个Sys.time()的差值。

start <- Sys.time()
## ... code here ... ##
end <- Sys.time()
end - start

这将以人类可读的格式打印结果,例如“2秒的时间差”。但是,由于单位可以变化(从“秒”到“分钟”到“天”),因此,如果多个运行时的单位不同,那么使用此方法在相同基础上比较它们就不太有用。

对于非交互目的,最好指定时间单位。

具体来说,Sys.time()返回一个POSIXct对象。取两个posixct的差值,给出一个difftime类的对象,该对象具有“units”属性。特别是' - '操作被定义为在与POSIXct一起使用时使用difftime()。也就是说,

time2 - time1

等于

difftime(time2, time1)

要指定units属性,添加一个units=参数,例如。

difftime(time2, time1, units="secs")

总而言之,可以使用Sys.time()用指定的单位(秒、分等)来测量运行时。

start <- Sys.time()
## ... code here ... ##
end <- Sys.time()
difftime(end, start, units="secs")

另一种简单但非常强大的方法是使用包profvis。它不仅测量代码的执行时间,还为您提供了执行每个函数的钻取。它也可以用于Shiny。

library(profvis)

profvis({
  #your code here
})

点击这里查看一些例子。

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

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

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