This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: [PATCH v2][BZ #12515] Improve precision of clock function
- From: Paul Eggert <eggert at cs dot ucla dot edu>
- To: Siddhesh Poyarekar <siddhesh at redhat dot com>
- Cc: libc-alpha at sourceware dot org
- Date: Tue, 21 May 2013 09:00:09 -0700
- Subject: Re: [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>
On 05/21/13 08:34, Siddhesh Poyarekar wrote:
> + return (clock_t) ((ts.tv_nsec * CLOCKS_PER_SEC) / 1000000000
> + + ts.tv_sec * CLOCKS_PER_SEC);
First, there's no need to cast to clock_t, and in general it's better
to avoid casts if they're not needed.
Second, ts.tv_nsec * CLOCKS_PER_SEC might overflow on a machine
with 32-bit 'long', and afterwards the resulting division by 1000000000
won't wrap around to the "correct" value.
How about this instead?
return (ts.tv_sec * CLOCKS_PER_SEC
+ ts.tv_nsec / (1000000000 / CLOCKS_PER_SEC));