Search code examples
rtiming

subtracting posixCT objects and not getting seconds


I'm getting weird units after I subtract POSIXct objects, which are returned from two calls to Sys.time(). I'm using Sys.time() to time some call to system()--something like this:

start <- Sys.time()
system("./something_complicated_that_takes_a_while")
end <- Sys.time()
cat(end - start, "seconds\n")

I get 1.81494815872775 seconds, which is very strange. The runtime was closer to 1.8 hours, though. Just to check, I can do this:

start <- Sys.time()
system("/bin/sleep 2")
end <- Sys.time()
cat(end - start, "seconds\n")

and I get 2.002262 seconds, so it's working fine here. Any idea what's going on here?


Solution

  • Your first code is ok , it is 1.8 hours not seconds , here is explanation

    a <- Sys.time()
    
    b <- Sys.time() + 2 * 60 *60 # i add 2 hours here
    
    b - a 
    
    #> Time difference of 2.000352 hours
    
    

    above the deference b - a gives the answer in hours not seconds , so if you want to use cat try

    cat(b-a  , attr(b - a , "units"))
    
    #> 2.000352 hours
    

    and if you want your output in seconds try this

    difftime(b , a , units = "secs")
    
    #> Time difference of 7201.266 secs