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