繁体   English   中英

R - 如何获得两点之间经过的时间?

[英]R - How to get the time elapsed between two points?

我尝试使用Sys.time来获取两点之间经过的时间。 但是,它不会以我喜欢的方式输出。

这是它现在的样子:

a <- Sys.time
...running stuff between these two points...
b <- Sys.time
c <- b - a
c
Time difference of 1.00558 hours

我只想要数字和单位。 我知道要获得我可以做的数字:

c[[1]]

但是,有时c的结果可能会给我几秒钟或几分钟的时间。 我只想要我有数字和单位以小时为单位的实例。 有没有人知道使用 Sys.time() (或任何替代方法)可以得到类似以下内容的方法:

if (units == "hours")
{
  if (number => 1)
  {
      #do something
  }
}

使用基数 R 的difftime可以让您获得不同单位的时间差。 休息是格式化。

a = Sys.time()
Sys.sleep(5)    #do something
b = Sys.time()    
paste0(round(as.numeric(difftime(time1 = b, time2 = a, units = "secs")), 3), " Seconds")
#[1] "5.091 Seconds"

您可以将所有内容作为system.time函数的参数进行评估。 它会以秒为单位为您提供经过的时间。

paste0(system.time( rnorm(1000000, 0, 1) )[3] / 3600, " hours")
# "2.58333333334172e-05 hours"

或者,您可以在评论中使用 Frank 的建议。 difftime(b, a, units = "hours")这在大多数情况下可能是主要的解决方案

tictoc包简化了这种计时。 它不返回小时,但我们可以创建一个新函数,将其基于秒的测量值转换为小时。

library(tictoc)

toc_hour <- function() {
  x <- toc()
  (x$toc - x$tic) / 3600
}

您通常使用tic()启动计时器并使用toc()停止它。

tic()
Sys.sleep(2)
toc()
# 2.02 sec elapsed

调用toc_hour()而不是toc()返回已经过去的小时数。

tic()
Sys.sleep(2)
toc_hour()
# 2.25 sec elapsed
#  elapsed 
# 0.000625 

它仍然打印小时数以上的秒数,但如果您捕获结果,它只会存储用于下游分析的小时数。

tic()
Sys.sleep(2)
x <- toc_hour()

if(x < 1) {print("This took under an hour")}

也许你可以试试“ tictoc”包。 如文档中所述,您可以执行以下操作:

tic()

#Do something

toc(log = TRUE, quiet = TRUE)

#Put the result in a log
log.txt <- tic.log(format = TRUE)

#Extract only the value
res <- gsub( " sec elapsed", "", unlist(log.txt))

#Clear the log
tic.clearlog()

这样, res只为您提供值并且以秒为单位,因此拥有数小时非常简单。 此外,如果您不清除日志,您可以将tic()toc()连续放入log.txt ,然后将gsub( " sec elapsed", "", unlist(log.txt))将为您提供一个字符串向量,每次迭代的值以秒为单位,这非常有用

我认为 lubridate 是最适合您的解决方案:

start <- Sys.time()
## Do Stuff here
end <- Sys.time()
elapsed <- lubridate::ymd_hms(end) - lubridate::ymd_hms(start) 
message(elapsed)

它应该返回一些有用的信息,例如:“12.1 小时的时差”

tictoc 包通常返回秒。 该软件包中的其他解决方案手动将其转换为其他单位,但我发现它看起来仍然不正确。 相反,使用 toc() 中的内置 func.toc 参数来更改输出。 例如:

toc_min <- function(tic,toc,msg="") {
  mins <- round((((toc-tic)/60)),2)
  outmsg <- paste0(mins, " minutes elapsed")
}

然后:

tic()
Sys.sleep(1)
toc(func.toc=toc_min)

返回

0.02 minutes elapsed

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM