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