Blame manual/examples/timeval_subtract.c

Packit 6c4009
/* struct timeval subtraction.
Packit 6c4009
   Copyright (C) 1991-2018 Free Software Foundation, Inc.
Packit 6c4009
Packit 6c4009
   This program is free software; you can redistribute it and/or
Packit 6c4009
   modify it under the terms of the GNU General Public License
Packit 6c4009
   as published by the Free Software Foundation; either version 2
Packit 6c4009
   of the License, or (at your option) any later version.
Packit 6c4009
Packit 6c4009
   This program is distributed in the hope that it will be useful,
Packit 6c4009
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 6c4009
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 6c4009
   GNU General Public License for more details.
Packit 6c4009
Packit 6c4009
   You should have received a copy of the GNU General Public License
Packit 6c4009
   along with this program; if not, if not, see <http://www.gnu.org/licenses/>.
Packit 6c4009
*/
Packit 6c4009
Packit 6c4009
/* Subtract the `struct timeval' values X and Y,
Packit 6c4009
   storing the result in RESULT.
Packit 6c4009
   Return 1 if the difference is negative, otherwise 0.  */
Packit 6c4009
Packit 6c4009
int
Packit 6c4009
timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
Packit 6c4009
{
Packit 6c4009
  /* Perform the carry for the later subtraction by updating @var{y}. */
Packit 6c4009
  if (x->tv_usec < y->tv_usec) {
Packit 6c4009
    int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
Packit 6c4009
    y->tv_usec -= 1000000 * nsec;
Packit 6c4009
    y->tv_sec += nsec;
Packit 6c4009
  }
Packit 6c4009
  if (x->tv_usec - y->tv_usec > 1000000) {
Packit 6c4009
    int nsec = (x->tv_usec - y->tv_usec) / 1000000;
Packit 6c4009
    y->tv_usec += 1000000 * nsec;
Packit 6c4009
    y->tv_sec -= nsec;
Packit 6c4009
  }
Packit 6c4009
Packit 6c4009
  /* Compute the time remaining to wait.
Packit 6c4009
     @code{tv_usec} is certainly positive. */
Packit 6c4009
  result->tv_sec = x->tv_sec - y->tv_sec;
Packit 6c4009
  result->tv_usec = x->tv_usec - y->tv_usec;
Packit 6c4009
Packit 6c4009
  /* Return 1 if result is negative. */
Packit 6c4009
  return x->tv_sec < y->tv_sec;
Packit 6c4009
}