In my R script when I want to calculate the running time of a function I use ''' start <- Sys.time() function finish <- Sys.time() difftime(finish, start) ''' The answer that I get from these codes is: " Time difference of 6.60801 mins" I want to see the time format in hours:minutes:seconds. In other words: How can I get the following message as the response of running my codes? "Time difference of 6:36 mins" Thanks for your help
CodePudding user response:
We can use as_hms
from the hms
package.
library(hms)
start <- Sys.time()
finish <- Sys.time()
as_hms(difftime(finish, start))
# 00:00:00.00066
CodePudding user response:
You could use some modular math and put it in a small function, e.g.:
HMS <- \(x) sprintf('d:d:d', x %/% 60^2, x %% 60^2 %/% 60, floor(x %% 60^2 %% 60))
t0 <- Sys.time()
t11 <- t0 6.60801*60
t12 <- t0 25*60^2 31*60 56.7398
HMS(as.numeric(difftime(t11, t0, units='secs')))
# [1] "000:06:36"
HMS(as.numeric(difftime(t12, t0, units='secs')))
# [1] "025:31:56"