This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [ping2][PATCH v2][BZ #12515] Improve precision of clock function


On Tue, Jun 11, 2013 at 01:24:03PM -0700, Paul Eggert wrote:
> I've tried it both ways, and found wrapv to be simpler.  It's
> trivial to explain and to understand, whereas unsigned arithmetic
> can be verbose and error-prone.  For example, here's how to check
> for overflow when adding two integer time_t values A and B,
> assuming wrapv:
> 
>     time_t sum = a + b;
>     bool overflow = (sum < a) == (b < 0);
> 
> and here's how to do it with unsigned values, assuming
> wrapv only when converting unsigned to signed:
> 
>     static time_t
>     time_t_wrapv_add (time_t a, time_t b)
>     {
>       if (sizeof (time_t) <= sizeof (unsigned long int))
> 	return (unsigned long int) a + (unsigned long int) b;
>       else
> 	return (unsigned long long int) a + (unsigned long int) b;
>     }
>     ...
>     time_t sum = time_t_wrapv_add (a, b);
>     bool overflow = (sum < a) == (b < 0);

This is idiomatically wrong, even if it works. If your goal is to
prevent overflow rather than wrapping then testing if it happened,
here's the way to do it:

	if (ts.tv_sec > LONG_MAX/1000000
	 || ts.tv_nsec/1000 > LONG_MAX-1000000*ts.tv_sec)
		return -1;

(Taken from the code I recently committed to musl to deal with the
clock() overflow issue.)
                                 
Rich


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]