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