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

R-如何获得两点之间经过的时间?,r,time,R,Time,我尝试使用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的结果会给我几秒钟或几分钟的时间。我只想要实例,其中我有数字,当单位是小时。是否有人知道使用Sys.time()(或任何其

我尝试使用
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
的结果会给我几秒钟或几分钟的时间。我只想要实例,其中我有数字,当单位是小时。是否有人知道使用Sys.time()(或任何其他方法)可以获得如下结果:

也许你可以试试这个包裹。 如文档中所述,您可以执行以下操作:

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()
tic()
#做点什么
toc(log=TRUE,quiet=TRUE)
#将结果记录在日志中

log.txt我认为lubridate是您最快的解决方案:

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

start使用基本R的
difftime
可以获得不同单位的时差。Rest是格式化

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"

或者,你可以在评论中使用弗兰克的建议
difftime(b,a,units=“hours”)
这可能是大多数情况下的主要解决方案

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

library(tictoc)

toc_hour <- function() {
  x <- toc()
  (x$toc - x$tic) / 3600
}
调用
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")}
tic()
系统睡眠(2)

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

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

0.02 minutes elapsed

也许
difftime(b,a,units=“hours”)
或者其他什么,你真的不应该使用
c
作为变量名,因为它是一个重要的函数。正如@Frank所说,你可以指定difftime对象的单位。您还可以将其与数字进行比较,因此如果difftime对象以小时为单位,则可以执行mydiff>=2,如果超过2小时,则返回True。
start
end
已经
POSIXct
。您的解决方案中不需要
lubridate::ymd_hms
tic()
Sys.sleep(2)
x <- toc_hour()

if(x < 1) {print("This took under an hour")}
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