1 /* $NetBSD: difftime.c,v 1.15 2013/09/20 19:06:54 christos Exp $ */
4 ** This file is in the public domain, so clarified as of
5 ** 1996-06-05 by Arthur David Olson.
9 #if defined(LIBC_SCCS) && !defined(lint)
11 static char elsieid
[] = "@(#)difftime.c 8.1";
13 __RCSID("$NetBSD: difftime.c,v 1.15 2013/09/20 19:06:54 christos Exp $");
15 #endif /* LIBC_SCCS and not lint */
19 #include "private.h" /* for time_t and TYPE_SIGNED */
21 double ATTRIBUTE_CONST
22 difftime(const time_t time1
, const time_t time0
)
25 ** If (sizeof (double) > sizeof (time_t)) simply convert and subtract
26 ** (assuming that the larger type has more precision).
29 if (sizeof (double) > sizeof (time_t))
30 return (double) time1
- (double) time0
;
32 if (!TYPE_SIGNED(time_t)) {
34 ** The difference of two unsigned values can't overflow
35 ** if the minuend is greater than or equal to the subtrahend.
39 else return -(double) (time0
- time1
);
42 ** Handle cases where both time1 and time0 have the same sign
43 ** (meaning that their difference cannot overflow).
45 if ((time1
< 0) == (time0
< 0))
48 ** time1 and time0 have opposite signs.
49 ** Punt if uintmax_t is too narrow.
50 ** This suffers from double rounding; attempt to lessen that
51 ** by using long double temporaries.
54 if (sizeof (uintmax_t) < sizeof (time_t))
55 return (double) time1
- (double) time0
;
57 ** Stay calm...decent optimizers will eliminate the complexity below.
59 if (time1
>= 0 /* && time0 < 0 */)
60 return (uintmax_t) time1
+ (uintmax_t) (-(time0
+ 1)) + 1;
61 return -(double) ((uintmax_t) time0
+ (uintmax_t) (-(time1
+ 1)) + 1);