1/* struct timeval subtraction.
2 Copyright (C) 1991-2024 Free Software Foundation, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, see <https://www.gnu.org/licenses/>.
16*/
17
18/* Subtract the `struct timeval' values X and Y,
19 storing the result in RESULT.
20 Return 1 if the difference is negative, otherwise 0. */
21
22int
23timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
24{
25 /* Perform the carry for the later subtraction by updating @var{y}. */
26 if (x->tv_usec < y->tv_usec) {
27 int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
28 y->tv_usec -= 1000000 * nsec;
29 y->tv_sec += nsec;
30 }
31 if (x->tv_usec - y->tv_usec > 1000000) {
32 int nsec = (x->tv_usec - y->tv_usec) / 1000000;
33 y->tv_usec += 1000000 * nsec;
34 y->tv_sec -= nsec;
35 }
36
37 /* Compute the time remaining to wait.
38 @code{tv_usec} is certainly positive. */
39 result->tv_sec = x->tv_sec - y->tv_sec;
40 result->tv_usec = x->tv_usec - y->tv_usec;
41
42 /* Return 1 if result is negative. */
43 return x->tv_sec < y->tv_sec;
44}
45

source code of glibc/manual/examples/timeval_subtract.c