timeval_subtract.c 1.6 KB

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