home *** CD-ROM | disk | FTP | other *** search
/ Chip 1995 March / CHIP3.mdf / slackwar / a / util / util-lin.2 / util-lin / util-linux-2.2 / time / difftime.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-02-22  |  2.1 KB  |  75 lines

  1. #ifndef lint
  2. #ifndef NOID
  3. static char    elsieid[] = "@(#)difftime.c    7.5";
  4. #endif /* !defined NOID */
  5. #endif /* !defined lint */
  6.  
  7. /*LINTLIBRARY*/
  8.  
  9. #include "private.h"
  10.  
  11. /*
  12. ** Algorithm courtesy Paul Eggert (eggert@twinsun.com).
  13. */
  14.  
  15. #ifdef HAVE_LONG_DOUBLE
  16. #define long_double    long double
  17. #endif /* defined HAVE_LONG_DOUBLE */
  18. #ifndef HAVE_LONG_DOUBLE
  19. #define long_double    double
  20. #endif /* !defined HAVE_LONG_DOUBLE */
  21.  
  22. double
  23. difftime(time1, time0)
  24. const time_t    time1;
  25. const time_t    time0;
  26. {
  27.     time_t    delta;
  28.     time_t    hibit;
  29.  
  30.     if (sizeof(time_t) < sizeof(double))
  31.         return (double) time1 - (double) time0;
  32.     if (sizeof(time_t) < sizeof(long_double))
  33.         return (long_double) time1 - (long_double) time0;
  34.     if (time1 < time0)
  35.         return -difftime(time0, time1);
  36.     /*
  37.     ** As much as possible, avoid loss of precision
  38.     ** by computing the difference before converting to double.
  39.     */
  40.     delta = time1 - time0;
  41.     if (delta >= 0)
  42.         return delta;
  43.     /*
  44.     ** Repair delta overflow.
  45.     */
  46.     hibit = 1;
  47.     while ((hibit <<= 1) > 0)
  48.         continue;
  49.     /*
  50.     ** The following expression rounds twice, which means
  51.     ** the result may not be the closest to the true answer.
  52.     ** For example, suppose time_t is 64-bit signed int,
  53.     ** long_double is IEEE 754 double with default rounding,
  54.     ** time1 = 9223372036854775807 and time0 = -1536.
  55.     ** Then the true difference is 9223372036854777343,
  56.     ** which rounds to 9223372036854777856
  57.     ** with a total error of 513.
  58.     ** But delta overflows to -9223372036854774273,
  59.     ** which rounds to -9223372036854774784, and correcting
  60.     ** this by subtracting 2 * (long_double) hibit
  61.     ** (i.e. by adding 2**64 = 18446744073709551616)
  62.     ** yields 9223372036854776832, which
  63.     ** rounds to 9223372036854775808
  64.     ** with a total error of 1535 instead.
  65.     ** This problem occurs only with very large differences.
  66.     ** It's too painful to fix this portably.
  67.     ** We are not alone in this problem;
  68.     ** many C compilers round twice when converting
  69.     ** large unsigned types to small floating types,
  70.     ** so if time_t is unsigned the "return delta" above
  71.     ** has the same double-rounding problem.
  72.     */
  73.     return delta - 2 * (long_double) hibit;
  74. }
  75.