打印脚本在 R 中 运行 的时间

Print the time a script has been running in R

对于简单的自制基准测试,我想在我的 R 脚本中添加一个计时器,以便我知道它已经持续了多长时间 运行。这是一个释放大量数据的脚本,因此可能需要一个多小时才能完成。因此,我正在寻找一种方法来告诉我脚本 运行.

的确切时间

我得到的想法是:

old = getCurrentTime()

# Do the rest of my script

(new = getCurrentTime() - old)

我不知道这是否有意义,但似乎最好的方法是在后台没有计数器 运行 的情况下,比较脚本的开始时间和时间最后并打印差异。但是,我不确定如何在 R 中获取时间、获取差异并将其格式化为 hh:mm:ss

您可以使用Sys.time()

old <- Sys.time() # get start time

# some code
#...

# print elapsed time
new <- Sys.time() - old # calculate difference
print(new) # print in nice format

但是,还有 microbenchmark 包,用于使用多次试验等进行更复杂/准确的计时。

您的一般方法是正确的,并且可能是实现此目的的最常规方法,与编程语言无关。但是,减去两个 POSIXt 个对象将得到一个 class difftime 的对象,其中测量单位是自动选择的(取决于差异的大小),而不是 "HH:MM:SS" 您正在寻找的格式。编写函数 return 这种格式非常简单,例如像

hms_span <- function(start, end) {
  dsec <- as.numeric(difftime(end, start, unit = "secs"))
  hours <- floor(dsec / 3600)
  minutes <- floor((dsec - 3600 * hours) / 60)
  seconds <- dsec - 3600*hours - 60*minutes
  paste0(
    sapply(c(hours, minutes, seconds), function(x) {
      formatC(x, width = 2, format = "d", flag = "0")
    }), collapse = ":")
}

(t0 <- Sys.time() - 3600 * 8.543)
#[1] "2015-08-19 03:48:36 EDT"
(t1 <- Sys.time())
#[1] "2015-08-19 12:19:24 EDT
R> hms_span(t0, t1)
#[1] "08:32:34"