xref: /openbsd-src/lib/libc/time/difftime.c (revision df930be708d50e9715f173caa26ffe1b7599b157)
1 /*	$NetBSD: difftime.c,v 1.2 1995/03/09 23:41:15 jtc Exp $	*/
2 
3 #ifndef lint
4 #ifndef NOID
5 static char	elsieid[] = "@(#)difftime.c	7.5";
6 #endif /* !defined NOID */
7 #endif /* !defined lint */
8 
9 /*LINTLIBRARY*/
10 
11 #include "private.h"
12 
13 /*
14 ** Algorithm courtesy Paul Eggert (eggert@twinsun.com).
15 */
16 
17 #ifdef HAVE_LONG_DOUBLE
18 #define long_double	long double
19 #endif /* defined HAVE_LONG_DOUBLE */
20 #ifndef HAVE_LONG_DOUBLE
21 #define long_double	double
22 #endif /* !defined HAVE_LONG_DOUBLE */
23 
24 double
25 difftime(time1, time0)
26 const time_t	time1;
27 const time_t	time0;
28 {
29 	time_t	delta;
30 	time_t	hibit;
31 
32 	if (sizeof(time_t) < sizeof(double))
33 		return (double) time1 - (double) time0;
34 	if (sizeof(time_t) < sizeof(long_double))
35 		return (long_double) time1 - (long_double) time0;
36 	if (time1 < time0)
37 		return -difftime(time0, time1);
38 	/*
39 	** As much as possible, avoid loss of precision
40 	** by computing the difference before converting to double.
41 	*/
42 	delta = time1 - time0;
43 	if (delta >= 0)
44 		return delta;
45 	/*
46 	** Repair delta overflow.
47 	*/
48 	hibit = 1;
49 	while ((hibit <<= 1) > 0)
50 		continue;
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 	** many 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.
74 	*/
75 	return delta - 2 * (long_double) hibit;
76 }
77