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