difftime

Olson, Arthur David (NIH/NCI) olsona at dc37a.nci.nih.gov
Thu Oct 21 14:36:17 UTC 2004


So...can we apply our hard-earned knowledge of modular arithmetic to the
task of getting difftime to do the right thing in the face of the various
types that time_t is allowed to assume?
A possibility would be to add to private.h...

------- private.h -------
*** /tmp/geta29733	Thu Oct 21 10:29:48 2004
--- /tmp/getb29733	Thu Oct 21 10:29:48 2004
***************
*** 21,27 ****
  
  #ifndef lint
  #ifndef NOID
! static char	privatehid[] = "@(#)private.h	7.54";
  #endif /* !defined NOID */
  #endif /* !defined lint */
  
--- 21,27 ----
  
  #ifndef lint
  #ifndef NOID
! static char	privatehid[] = "@(#)private.h	7.55";
  #endif /* !defined NOID */
  #endif /* !defined lint */
  
***************
*** 238,243 ****
--- 238,247 ----
  #define TYPE_SIGNED(type) (((type) -1) < 0)
  #endif /* !defined TYPE_SIGNED */
  
+ #ifndef TYPE_INTEGRAL
+ #define TYPE_INTEGRAL(type) (((type) 0.4) == 0)
+ #endif /* !defined TYPE_INTEGRAL */
+ 
  #ifndef INT_STRLEN_MAXIMUM
  /*
  ** 302 / 1000 is log10(2.0) rounded up.

...and then use the difftime.c that appears below.

				--ado

/*
** This file is in the public domain, so clarified as of
** June 5, 1996 by Arthur David Olson (arthur_david_olson at nih.gov).
*/

#ifndef lint
#ifndef NOID
static char	elsieid[] = "@(#)difftime.c	7.11";
#endif /* !defined NOID */
#endif /* !defined lint */

/*LINTLIBRARY*/

#include "sys/types.h"	/* for time_t */
#include "private.h"	/* for TYPE_INTEGRAL and TYPE_SIGNED */

double
difftime(time1, time0)
const time_t	time1;
const time_t	time0;
{
	if (!TYPE_INTEGRAL(time_t)) {
		/*
		** time_t is floating.
		** We can't apply % to floats.
		** Do the math in whichever of time_t or double is wider.
		*/
		if (sizeof (time_t) >= sizeof (double))
			return time1 - time0;
		else	return (double) time1 - (double) time0;
	} else {
		/*
		** time_t is integral.
		** As elsewhere in the time zone package,
		** use modular arithmetic to avoid overflow.
		*/
		register time_t	lead;
		register time_t	trail;

		lead = time1 / 2 - time0 / 2;
		trail = time1 % 2 - time0 % 2;
		return 2 * ((double) lead) + trail;
	}
}



More information about the tz mailing list