difftime.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* $OpenBSD: difftime.c,v 1.9 2005/08/08 08:05:38 espie Exp $ */
  2. /*
  3. ** This file is in the public domain, so clarified as of
  4. ** 1996-06-05 by Arthur David Olson.
  5. */
  6. /*LINTLIBRARY*/
  7. #include "private.h" /* for time_t, TYPE_INTEGRAL, and TYPE_SIGNED */
  8. double
  9. difftime(time1, time0)
  10. const time_t time1;
  11. const time_t time0;
  12. {
  13. /*
  14. ** If (sizeof (double) > sizeof (time_t)) simply convert and subtract
  15. ** (assuming that the larger type has more precision).
  16. ** This is the common real-world case circa 2004.
  17. */
  18. if (sizeof (double) > sizeof (time_t))
  19. return (double) time1 - (double) time0;
  20. if (!TYPE_INTEGRAL(time_t)) {
  21. /*
  22. ** time_t is floating.
  23. */
  24. return time1 - time0;
  25. }
  26. if (!TYPE_SIGNED(time_t)) {
  27. /*
  28. ** time_t is integral and unsigned.
  29. ** The difference of two unsigned values can't overflow
  30. ** if the minuend is greater than or equal to the subtrahend.
  31. */
  32. if (time1 >= time0)
  33. return time1 - time0;
  34. else return -((double) (time0 - time1));
  35. }
  36. /*
  37. ** time_t is integral and signed.
  38. ** Handle cases where both time1 and time0 have the same sign
  39. ** (meaning that their difference cannot overflow).
  40. */
  41. if ((time1 < 0) == (time0 < 0))
  42. return time1 - time0;
  43. /*
  44. ** time1 and time0 have opposite signs.
  45. ** Punt if unsigned long is too narrow.
  46. */
  47. if (sizeof (unsigned long) < sizeof (time_t))
  48. return (double) time1 - (double) time0;
  49. /*
  50. ** Stay calm...decent optimizers will eliminate the complexity below.
  51. */
  52. if (time1 >= 0 /* && time0 < 0 */)
  53. return (unsigned long) time1 +
  54. (unsigned long) (-(time0 + 1)) + 1;
  55. return -(double) ((unsigned long) time0 +
  56. (unsigned long) (-(time1 + 1)) + 1);
  57. }