difftime.c revision 1.1.1.4 1 /*
2 ** This file is in the public domain, so clarified as of
3 ** June 5, 1996 by Arthur David Olson (arthur_david_olson (at) nih.gov).
4 */
5
6 #ifndef lint
7 #ifndef NOID
8 static char elsieid[] = "@(#)difftime.c 7.9";
9 #endif /* !defined NOID */
10 #endif /* !defined lint */
11
12 /*LINTLIBRARY*/
13
14 #include "private.h"
15
16 /*
17 ** Algorithm courtesy Paul Eggert (eggert (at) twinsun.com).
18 */
19
20 #ifdef HAVE_LONG_DOUBLE
21 #define long_double long double
22 #endif /* defined HAVE_LONG_DOUBLE */
23 #ifndef HAVE_LONG_DOUBLE
24 #define long_double double
25 #endif /* !defined HAVE_LONG_DOUBLE */
26
27 double
28 difftime(time1, time0)
29 const time_t time1;
30 const time_t time0;
31 {
32 time_t delta;
33 time_t hibit;
34
35 {
36 time_t tt;
37 double d;
38 long_double ld;
39
40 if (sizeof tt < sizeof d)
41 return (double) time1 - (double) time0;
42 if (sizeof tt < sizeof ld)
43 return (long_double) time1 - (long_double) time0;
44 }
45 if (time1 < time0)
46 return -difftime(time0, time1);
47 /*
48 ** As much as possible, avoid loss of precision
49 ** by computing the difference before converting to double.
50 */
51 delta = time1 - time0;
52 if (delta >= 0)
53 return delta;
54 /*
55 ** Repair delta overflow.
56 */
57 hibit = (~ (time_t) 0) << (TYPE_BIT(time_t) - 1);
58 /*
59 ** The following expression rounds twice, which means
60 ** the result may not be the closest to the true answer.
61 ** For example, suppose time_t is 64-bit signed int,
62 ** long_double is IEEE 754 double with default rounding,
63 ** time1 = 9223372036854775807 and time0 = -1536.
64 ** Then the true difference is 9223372036854777343,
65 ** which rounds to 9223372036854777856
66 ** with a total error of 513.
67 ** But delta overflows to -9223372036854774273,
68 ** which rounds to -9223372036854774784, and correcting
69 ** this by subtracting 2 * (long_double) hibit
70 ** (i.e. by adding 2**64 = 18446744073709551616)
71 ** yields 9223372036854776832, which
72 ** rounds to 9223372036854775808
73 ** with a total error of 1535 instead.
74 ** This problem occurs only with very large differences.
75 ** It's too painful to fix this portably.
76 ** We are not alone in this problem;
77 ** some C compilers round twice when converting
78 ** large unsigned types to small floating types,
79 ** so if time_t is unsigned the "return delta" above
80 ** has the same double-rounding problem with those compilers.
81 */
82 return delta - 2 * (long_double) hibit;
83 }
84