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

Aly*_*ssa 5 time r difftime

I'm currently running a for loop code and at the end of each loop I am measuring the duration of the loop and print a message that tells the user how long did the loop take.

To get the duration I'm using

duration <- difftime(end_time, start_time) 
Run Code Online (Sandbox Code Playgroud)

And this is how I print the statement

print(paste("Loop", i, "took", duration, "to run.")). 
Run Code Online (Sandbox Code Playgroud)

The problem is the duration of each loop may range from 30 seconds to 1 hour. Putting the duration inside the paste just turns it into a number without the unit in it.

e.g.

print(paste("Loop", i, "took", duration, "to run.")). 
"Loop 5 took 10.5 to run"
Run Code Online (Sandbox Code Playgroud)

How do I get the unit from the difftime() in order to get something like: "Loop 5 took 10.5 minutes to run."

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

Jde*_*llo 7

调用unitsfromduration获取单位并通过子集获取数值duration

print(paste("Loop", i, "took", round(duration[[1]], 2),  units(duration), "to run."))
Run Code Online (Sandbox Code Playgroud)

下面是一个例子:

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."))
Run Code Online (Sandbox Code Playgroud)

结果:

[1] "Loop 1 took 6.97 secs to run."
Run Code Online (Sandbox Code Playgroud)

根据持续时间的范围,该单位将是自动的。请参阅此其他示例:

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."))
Run Code Online (Sandbox Code Playgroud)

结果:

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