Search code examples
rtimedifftime

How do you extract the time unit when using 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) 

And this is how I print the statement

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

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"

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

PS: Some may suggest standardizing the duration by declaring the "unit" argument in difftime() but I want the duration to be easily understood by the user that's why I set the unit to default "auto".


Solution

  • Call units from duration to get the unit and get the numeric value by subsetting duration:

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

    Here is an example:

    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."))
    

    Result:

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

    The unit would be automatic depending on the range of the duration. See this ohter example:

    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."))
    

    Result:

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