Difftime code

Paul Eggert eggert at CS.UCLA.EDU
Thu Aug 5 22:37:11 UTC 2004


Wow, that's pretty a complicated way to subtract two numbers.  :-)

If we can assume uintmax_t (by typedefing it on older hosts), isn't
there a much simpler approach entirely?  Something like the following.

The idea behind the sizeof test is to avoid "long double" if it's safe
to do so, since long double is expensive on some hosts.  This use of
sizeof conforms even to the weird C99 rules.  (Tricky, huh?)


#define TYPE_FLOATING(type) ((type) 0.5 != 0)
#define TYPE_SIGNED(type) (((type) -1) < 0)
#define TYPE_BIT(type) (sizeof (type) * CHAR_BIT)

static double
simple_difftime (time_t time1, time_t time0)
{
  if (TYPE_SIGNED (time_t))
    return (uintmax_t) time1 - (uintmax_t) time0;
  else
    return time1 - time0;
}

double
difftime (time_t time1, time_t time0)
{
  if (TYPE_BIT (time_t) <= DBL_MANT_DIG
      || (TYPE_FLOATING (time_t) && sizeof (time_t) != sizeof (long double)))
    return (double) time1 - (double) time0;
  if (TYPE_FLOATING (time_t))
    return (long_double) time1 - (long_double) time0;

  if (time1 < time0)
    return -simple_difftime (time0, time1);
  else
    return simple_difftime (time1, time0);
}



More information about the tz mailing list