[PATCH v2][BZ #12515] Improve precision of clock function
Paul Eggert
eggert@cs.ucla.edu
Tue May 21 16:00:00 GMT 2013
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));
More information about the Libc-alpha
mailing list