ykz said:
what format shall i use to print clock_t variables?
i tried %f, %i, %S or %M(seconds or minutes, as said in K&R2 book),
all seem not to work.
the code is like:
#include <time.h>
clock_t t1, t2;
t1 = clock();
/* codes you want to time */
t2 = clock() - t1;
my question is: how to print out the correct value in t2 ?
or am i using clock_t correctly?
thanks for your help.
There are multiple layers of obscurity and opacity here,
since all the Standard says about `clock_t' is that it is an
"arithmetic type." Different implementations are free to use
different types, so there's no format specifier that is sure
to work on all implementations.
Furthermore, the precision[*] of a `clock_t' value is
also implementation-dependent; you need to divide by the
implementation-defined value `CLOCKS_PER_SEC' to convert
it to seconds. The division is just a little bit tricky,
though, because `CLOCKS_PER_SEC' is also a `clock_t' value,
and if the implementation has chosen some flavor of integer
as its `clock_t', the division will be an integer division
and will discard any fraction.
Some people therefore recommend an explicit conversion
to `double' before doing the division, and then printing
the quotient (in seconds) with some kind of "%f" specifier:
printf ("%.2f\n", (double)t2 / CLOCKS_PER_SEC);
However, it is just barely possible that this could be
wrong. `clock_t' could be *any* arithmetic type -- and
if the implementation uses `long double' as its `clock_t',
not only would the conversion specifier need to be "%Lf"
instead of "%f", but there's also the fear that chopping
the `long double' down to `double' might lose precision
or even be invalid altogether. So the next refinement is
printf ("%.2Lf\n", (long double)t2 / CLOCKS_PER_SEC);
.... but this is also unsatisfactory, to me at least. Using
all the potentially gruesome machinery of `long double' just
to cater to an unlikely "corner case" is irksome. I finally
settled on this scheme:
printf ("%.2f\n",
(double)( (t2 + 0.0) / CLOCKS_PER_SEC) );
The `t2 + 0.0' piece promotes the numerator to at least
`double', and leaves it at `long double' if that's what a
`clock_t' is anyhow. Then the division is carried out in
`double' or `long double'. Finally, the quotient (now in
seconds) is converted to `double' if it was `long double'
or left as `double' if that's what it already was, and the
`double' result is then printed with "%f".