23

I have 2 variables of type time_t - varEnd and varStart. Now in order to see the difference between them Either I can do

varEnd - varStart; 

or

difftime(varEnd, varStart);

and both returns number of seconds.

Please let me know, if they have any difference? or which is the recommended one?

devnull
  • 118,548
  • 33
  • 236
  • 227
Naresh
  • 658
  • 1
  • 7
  • 22
  • 2
    Why is this tagged as `C++` ? – Paul R Dec 13 '12 at 09:07
  • 1
    @PaulR: `difftime()` exists in both C and C++. – Keith Thompson Dec 13 '12 at 18:01
  • 1
    Well you can probably call it form Pascal or FORTRAN too, but it doesn't make this a Pascal or FORTRAN question. ;) – Paul R Dec 13 '12 at 18:25
  • Probably we should add more tags, if the function can directly be called from many other languages and relavent to that community deleveoper rather than removing them, because it increases the search probability and helps that community as well. – Naresh Dec 18 '12 at 06:57

2 Answers2

37

The language specifies that time_t is an arithmetic type capable of representing times. It doesn't require it to represent times in any particular way.

If time_t represents time as the number of seconds since some moment, the - operator will correctly compute the difference in seconds between two time_t values.

If it doesn't (say, if the granularity is one millisecond, or if the bits of a time_t are divided into groups representing years, months, days, etc.), then the - operator can yield meaningless results.

The difftime() function, on the other hand, "knows" how a time_t represents a time, and uses that information to compute the difference in seconds.

On most implementations, simple subtraction and difftime() happen to do the same thing -- but only difftime() is guaranteed to work correctly on all implementations.

Another difference: difftime() returns a result of the floating-point type double, while "-" on time_t values yields a result of type time_t. In most cases the result will be implicitly converted to the type of whatever you assign it to, but if time_t happens to be an unsigned integer type, subtraction of a later time from an earlier time will yield a very large value rather than a negative value. Every system I've seen implements time_t as a 32-bit or 64-bit signed integer type, but using an unsigned type is permitted -- one more reason that simple subtraction of time_t values isn't necessary meaningful.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
2

difftime() returns a floating point double, just subtracting them doesn't unless you cast them to double first.
source: here

Kevin
  • 2,739
  • 33
  • 57
  • 1
    Yes, but even converting both `time_t` operands to `double` before subtracting them isn't guaranteed to do the same thing as `difftime` -- which is why `difftime` exists. See my answer. – Keith Thompson Aug 29 '13 at 18:55