blob: ff78f03c5705e9eda5da939e49df643006afd110 [file] [log] [blame]
Almaz Mingaleev5411aff2022-02-11 12:27:12 +00001/* Return the difference between two timestamps. */
2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003/*
4** This file is in the public domain, so clarified as of
5** 1996-06-05 by Arthur David Olson.
6*/
7
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08008/*LINTLIBRARY*/
9
Elliott Hughese0d0b152013-09-27 00:04:30 -070010#include "private.h" /* for time_t and TYPE_SIGNED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080011
Elliott Hughes9fb22a32015-10-07 17:13:40 -070012/* Return -X as a double. Using this avoids casting to 'double'. */
13static double
14dminus(double x)
15{
16 return -x;
17}
18
Almaz Mingaleev5411aff2022-02-11 12:27:12 +000019double
Elliott Hughes9fb22a32015-10-07 17:13:40 -070020difftime(time_t time1, time_t time0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080021{
Elliott Hughesce4783c2013-07-12 17:31:11 -070022 /*
Elliott Hughes9fb22a32015-10-07 17:13:40 -070023 ** If double is large enough, simply convert and subtract
Elliott Hughesce4783c2013-07-12 17:31:11 -070024 ** (assuming that the larger type has more precision).
25 */
Almaz Mingaleev5411aff2022-02-11 12:27:12 +000026 if (sizeof(time_t) < sizeof(double)) {
Elliott Hughes9fb22a32015-10-07 17:13:40 -070027 double t1 = time1, t0 = time0;
28 return t1 - t0;
Elliott Hughesce4783c2013-07-12 17:31:11 -070029 }
Elliott Hughes9fb22a32015-10-07 17:13:40 -070030
31 /*
32 ** The difference of two unsigned values can't overflow
33 ** if the minuend is greater than or equal to the subtrahend.
34 */
35 if (!TYPE_SIGNED(time_t))
36 return time0 <= time1 ? time1 - time0 : dminus(time0 - time1);
37
38 /* Use uintmax_t if wide enough. */
Almaz Mingaleev5411aff2022-02-11 12:27:12 +000039 if (sizeof(time_t) <= sizeof(uintmax_t)) {
Elliott Hughes9fb22a32015-10-07 17:13:40 -070040 uintmax_t t1 = time1, t0 = time0;
41 return time0 <= time1 ? t1 - t0 : dminus(t0 - t1);
42 }
43
Elliott Hughesce4783c2013-07-12 17:31:11 -070044 /*
Elliott Hughesce4783c2013-07-12 17:31:11 -070045 ** Handle cases where both time1 and time0 have the same sign
46 ** (meaning that their difference cannot overflow).
47 */
48 if ((time1 < 0) == (time0 < 0))
Elliott Hughes9fb22a32015-10-07 17:13:40 -070049 return time1 - time0;
50
Elliott Hughesce4783c2013-07-12 17:31:11 -070051 /*
Elliott Hughes9fb22a32015-10-07 17:13:40 -070052 ** The values have opposite signs and uintmax_t is too narrow.
Elliott Hughesce4783c2013-07-12 17:31:11 -070053 ** This suffers from double rounding; attempt to lessen that
54 ** by using long double temporaries.
55 */
Elliott Hughes9fb22a32015-10-07 17:13:40 -070056 {
57 long double t1 = time1, t0 = time0;
58 return t1 - t0;
59 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080060}