This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: [ping2][PATCH v2][BZ #12515] Improve precision of clock function
- From: Rich Felker <dalias at aerifal dot cx>
- To: Paul Eggert <eggert at cs dot ucla dot edu>
- Cc: Siddhesh Poyarekar <siddhesh at redhat dot com>, libc-alpha at sourceware dot org
- Date: Tue, 11 Jun 2013 19:08:34 -0400
- Subject: Re: [ping2][PATCH v2][BZ #12515] Improve precision of clock function
- References: <20130521145611 dot GM8927 at spoyarek dot pnq dot redhat dot com> <20130521151839 dot GA18430 at domone dot kolej dot mff dot cuni dot cz> <20130521153442 dot GO8927 at spoyarek dot pnq dot redhat dot com> <519B9A09 dot 6030305 at cs dot ucla dot edu> <20130521161441 dot GQ8927 at spoyarek dot pnq dot redhat dot com> <20130603092604 dot GL2145 at spoyarek dot pnq dot redhat dot com> <20130610083821 dot GD1570 at spoyarek dot pnq dot redhat dot com> <51B66522 dot 1060008 at cs dot ucla dot edu> <20130611135422 dot GK8010 at spoyarek dot pnq dot redhat dot com> <51B78763 dot 1080707 at cs dot ucla dot edu>
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