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