xref: /openbsd-src/lib/libc/time/difftime.c (revision d79de7ff7570de640252ff3ab8ae7105f99e6475)
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.9";
8 static char rcsid[] = "$OpenBSD: difftime.c,v 1.6 2002/04/04 19:12:09 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 	{
35 		time_t		tt;
36 		double		d;
37 		long_double	ld;
38 
39 		if (sizeof tt < sizeof d)
40 			return (double) time1 - (double) time0;
41 		if (sizeof tt < sizeof ld)
42 			return (long_double) time1 - (long_double) time0;
43 	}
44 	if (time1 < time0)
45 		return -difftime(time0, time1);
46 	/*
47 	** As much as possible, avoid loss of precision
48 	** by computing the difference before converting to double.
49 	*/
50 	delta = time1 - time0;
51 	if (delta >= 0)
52 		return delta;
53 	/*
54 	** Repair delta overflow.
55 	*/
56 	hibit = (~ (time_t) 0) << (TYPE_BIT(time_t) - 1);
57 	/*
58 	** The following expression rounds twice, which means
59 	** the result may not be the closest to the true answer.
60 	** For example, suppose time_t is 64-bit signed int,
61 	** long_double is IEEE 754 double with default rounding,
62 	** time1 = 9223372036854775807 and time0 = -1536.
63 	** Then the true difference is 9223372036854777343,
64 	** which rounds to 9223372036854777856
65 	** with a total error of 513.
66 	** But delta overflows to -9223372036854774273,
67 	** which rounds to -9223372036854774784, and correcting
68 	** this by subtracting 2 * (long_double) hibit
69 	** (i.e. by adding 2**64 = 18446744073709551616)
70 	** yields 9223372036854776832, which
71 	** rounds to 9223372036854775808
72 	** with a total error of 1535 instead.
73 	** This problem occurs only with very large differences.
74 	** It's too painful to fix this portably.
75 	** We are not alone in this problem;
76 	** some C compilers round twice when converting
77 	** large unsigned types to small floating types,
78 	** so if time_t is unsigned the "return delta" above
79 	** has the same double-rounding problem with those compilers.
80 	*/
81 	return delta - 2 * (long_double) hibit;
82 }
83