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