使用 difftime() 时如何提取时间单位?

How do you extract the time unit when using difftime()?

我目前 运行 一个 for 循环代码,在每个循环结束时我测量循环的持续时间并打印一条消息,告诉用户循环花费了多长时间。

获取我正在使用的时长

duration <- difftime(end_time, start_time) 

这就是我打印语句的方式

print(paste("Loop", i, "took", duration, "to run.")). 

问题是每个循环的持续时间可能在 30 秒到 1 小时之间。将持续时间放在粘贴中只会将其变成一个没有单位的数字。

例如

print(paste("Loop", i, "took", duration, "to run.")). 
"Loop 5 took 10.5 to run"

如何从 difftime() 中获取单位以获得类似的东西:"Loop 5 took 10.5 minutes to run."

PS:有些人可能建议通过在 difftime() 中声明 "unit" 参数来标准化持续时间,但我希望用户能够轻松理解持续时间,这就是我将单位设置为默认值的原因"auto"。

一种方法是使用 capture.output

捕获 difftime 的输出
start_time <- as.POSIXct('2019-01-01 02:34:00')
end_time <- as.POSIXct('2019-01-01 03:14:00')

paste("Loop 5 took", capture.output(difftime(end_time, start_time)), "to run.")
#[1] "Loop 5 took Time difference of 40 mins to run."

现在您可以更改输出以使其有意义,比如从输出

中删除 "Time difference of "
sent <- capture.output(difftime(end_time, start_time))
paste("Loop 5 took",sub("Time difference of ","", sent) , "to run.")
#[1] "Loop 5 took 40 mins to run."

另一个输入

start_time <- as.POSIXct('2019-01-01 02:34:00')
end_time <- as.POSIXct('2019-01-01 02:34:50')

sent <- capture.output(difftime(end_time, start_time))
paste("Loop 5 took",sub("Time difference of ","", sent) , "to run.")
#[1] "Loop 5 took 50 secs to run."

duration调用units获取单位,通过子集duration获取数值:

print(paste("Loop", i, "took", round(duration[[1]], 2),  units(duration), "to run."))

这是一个例子:

start_time <- Sys.time()

# few seconds later
end_time <- Sys.time()

duration <- difftime(end_time, start_time)

print(paste("Loop", 1, "took", round(duration[[1]], 2),  units(duration), "to run."))

结果:

[1] "Loop 1 took 6.97 secs to run."

该单位将根据持续时间的范围自动调整。请参阅以下其他示例:

start_time <- Sys.time()

# few days later
end_time <- as.Date("2019-01-23")

duration <- difftime(end_time, start_time)

print(paste("Loop", 1, "took", round(duration[[1]], 2),  units(duration), "to run."))

结果:

> print(paste("Loop", 1, "took", round(duration[[1]], 2),  units(duration), "to run."))
[1] "Loop 1 took 5.9 days to run."

你应该可以通过 units(duration) 得到它。