]>
git.saurik.com Git - apple/libc.git/blob - stdtime/FreeBSD/difftime.c
b7fa1b0faba48609ee0a1509449d1165ecadb743
2 ** This file is in the public domain, so clarified as of
3 ** June 5, 1996 by Arthur David Olson (arthur_david_olson@nih.gov).
9 static char elsieid
[] __unused
= "@(#)difftime.c 7.7";
10 #endif /* !defined NOID */
11 #endif /* !defined lint */
12 __FBSDID("$FreeBSD: src/lib/libc/stdtime/difftime.c,v 1.7 2003/02/16 17:29:11 nectar Exp $");
16 #include "namespace.h"
18 #include "un-namespace.h"
21 ** Algorithm courtesy Paul Eggert (eggert@twinsun.com).
24 #ifdef HAVE_LONG_DOUBLE
25 #define long_double long double
26 #endif /* defined HAVE_LONG_DOUBLE */
27 #ifndef HAVE_LONG_DOUBLE
28 #define long_double double
29 #endif /* !defined HAVE_LONG_DOUBLE */
32 difftime(time1
, time0
)
39 if (sizeof(time_t) < sizeof(double))
40 return (double) time1
- (double) time0
;
41 if (sizeof(time_t) < sizeof(long_double
))
42 return (long_double
) time1
- (long_double
) time0
;
44 return -difftime(time0
, time1
);
46 ** As much as possible, avoid loss of precision
47 ** by computing the difference before converting to double.
49 delta
= time1
- time0
;
53 ** Repair delta overflow.
55 hibit
= (~ (time_t) 0) << (TYPE_BIT(time_t) - 1);
57 ** The following expression rounds twice, which means
58 ** the result may not be the closest to the true answer.
59 ** For example, suppose time_t is 64-bit signed int,
60 ** long_double is IEEE 754 double with default rounding,
61 ** time1 = 9223372036854775807 and time0 = -1536.
62 ** Then the true difference is 9223372036854777343,
63 ** which rounds to 9223372036854777856
64 ** with a total error of 513.
65 ** But delta overflows to -9223372036854774273,
66 ** which rounds to -9223372036854774784, and correcting
67 ** this by subtracting 2 * (long_double) hibit
68 ** (i.e. by adding 2**64 = 18446744073709551616)
69 ** yields 9223372036854776832, which
70 ** rounds to 9223372036854775808
71 ** with a total error of 1535 instead.
72 ** This problem occurs only with very large differences.
73 ** It's too painful to fix this portably.
74 ** We are not alone in this problem;
75 ** some C compilers round twice when converting
76 ** large unsigned types to small floating types,
77 ** so if time_t is unsigned the "return delta" above
78 ** has the same double-rounding problem with those compilers.
80 return delta
- 2 * (long_double
) hibit
;