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