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