R/get_elapsed_time_str.R

Defines functions get_elapsed_time_str

Documented in get_elapsed_time_str

#' Returns the elapsed time since start_time.
#'
## Copyright(c) 2017-2020 R. Mark Sharp
## This file is part of nprcgenekeepr
#' Taken from github.com/rmsharp/rmsutilityr
#'
#' @return A character vector describing the passage of time in hours, minutes,
#' and seconds.
#'
#' @examples
#' \donttest{
#' start_time <- proc.time()
#' ## do something
#' elapsed_time <- get_elapsed_time_str(start_time)
#' }
#'
#' @param start_time a POSIXct time object
#' @importFrom stringi stri_c
#' @export
get_elapsed_time_str <- function(start_time) {
  # To use: collect the start_time at the beginning of the script with
  # start_time <- proc.time()
  # At the end call this function using start_time as the sole argument
  # elapsed_time <- get_elapsed_time_str(start_time)
  total_seconds <- (proc.time()[[3]] - start_time[[3]])
  total_minutes <- total_seconds / 60
  hours <- floor(total_minutes / 60)
  minutes <- floor(total_minutes - hours * 60)
  seconds <- round(total_seconds - (hours * 3600) - (minutes * 60), 0)
  hours_str <- ifelse(hours > 0, stri_c(hours, " hours, "), "")
  minutes_str <- ifelse(minutes > 0, stri_c(minutes, " minutes and "), "")
  seconds_str <- stri_c(seconds, " seconds.")
  stri_c(hours_str, minutes_str, seconds_str)
}
rmsharp/nprcmanager documentation built on April 24, 2021, 3:13 p.m.