R - How to get the time elapsed between two points?

Viewed 2943

I've tried to use Sys.time to get the time elapsed between two points. However, it doesn't output in a way I like.

This is how it looks now:

a <- Sys.time
...running stuff between these two points...
b <- Sys.time
c <- b - a
c
Time difference of 1.00558 hours

I only want the number and the units. I know that to get just the number I can do:

c[[1]]

However, sometimes the result of c can give me seconds or minutes. I only want instances wherein I have the number and when the units are in hours. Does anyone know of a way such that I would get something like the following, using Sys.time() (or any alternative):

if (units == "hours")
{
  if (number => 1)
  {
      #do something
  }
}
6 Answers

The tictoc package normally returns seconds. The other solutions from this package manually converts this to other units but I find it still doesn't look right. Instead, use the built-in func.toc argument in toc() to change the output. For example:

toc_min <- function(tic,toc,msg="") {
  mins <- round((((toc-tic)/60)),2)
  outmsg <- paste0(mins, " minutes elapsed")
}

And then:

tic()
Sys.sleep(1)
toc(func.toc=toc_min)

returns

0.02 minutes elapsed
Related