Home | History | Annotate | Line # | Download | only in time
difftime.c revision 1.16.2.1
      1     /*	$NetBSD: difftime.c,v 1.16.2.1 2017/03/20 06:56:58 pgoyette Exp $	*/
      2     
      3     /*
      4     ** This file is in the public domain, so clarified as of
      5     ** 1996-06-05 by Arthur David Olson.
      6     */
      7     
      8     #include <sys/cdefs.h>
      9     #if defined(LIBC_SCCS) && !defined(lint)
     10     #if 0
     11     static char	elsieid[] = "@(#)difftime.c	8.1";
     12     #else
     13     __RCSID("$NetBSD: difftime.c,v 1.16.2.1 2017/03/20 06:56:58 pgoyette Exp $");
     14     #endif
     15     #endif /* LIBC_SCCS and not lint */
     16     
     17     /*LINTLIBRARY*/
     18     
     19     #include "private.h"	/* for time_t and TYPE_SIGNED */
     20     
     21     /* Return -X as a double.  Using this avoids casting to 'double'.  */
     22     static double
     23     dminus(double x)
     24     {
     25     	return -x;
     26     }
     27     
     28     double ATTRIBUTE_CONST
     29     difftime(time_t time1, time_t time0)
     30     {
     31     	/*
     32     	** If double is large enough, simply convert and subtract
     33     	** (assuming that the larger type has more precision).
     34     	*/
     35     	/*CONSTCOND*/
     36     	if (sizeof (time_t) < sizeof (double)) {
     37     		double t1 = time1, t0 = time0;
     38     		return t1 - t0;
     39      	}
     40     
     41     	/*
     42     	** The difference of two unsigned values can't overflow
     43     	** if the minuend is greater than or equal to the subtrahend.
     44     	*/
     45     	if (!TYPE_SIGNED(time_t))
     46     		return time0 <= time1 ? time1 - time0 : dminus(time0 - time1);
     47     
     48     	/* Use uintmax_t if wide enough.  */
     49     	/*CONSTCOND*/
     50     	if (sizeof (time_t) <= sizeof (uintmax_t)) {
     51     		uintmax_t t1 = time1, t0 = time0;
     52     		return time0 <= time1 ? t1 - t0 : dminus(t0 - t1);
     53     	}
     54     
     55     	/*
     56     	** Handle cases where both time1 and time0 have the same sign
     57     	** (meaning that their difference cannot overflow).
     58     	*/
     59     	if ((time1 < 0) == (time0 < 0))
     60     		return time1 - time0;
     61     
     62     	/*
     63     	** The values have opposite signs and uintmax_t is too narrow.
     64     	** This suffers from double rounding; attempt to lessen that
     65     	** by using long double temporaries.
     66     	*/
     67     	{
     68     		long double t1 = time1, t0 = time0;
     69     		return t1 - t0;
     70     	}
     71     }
     72