...
Two common errors are made when performing this operation. They are illustrated below.
Non
...
Compliant Code
...
:
Code Block |
---|
int run_big_program() { clock_t start, finish; int seconds; start = clock(); run_long_program() finish = clock(); seconds = ((finish-start)/CLOCKS_PER_SEC); return seconds; } |
...
C99 Section 7.23.1 states that CLOCKS_PER_SEC
expands to a constant expression with type clock_t
that is the number per second of the value returned by the clock()
function, so dividing by CLOCKS_PER_SEC
will net you the number of seconds. What is not specified, however, is the type that will be yielded by dividing CLOCKS_PER_SEC
. The best recommendation is to look at the types defined in time.h and use a compatible (and large, to prevent overflow) type. The convention for linux and most x86 architectures seems to be to use a double.
Compliant
...
Code:
Code Block |
---|
double run_big_program () { clock_t start, finish; double seconds; start = clock(); if (start = (clock_t)(-1)){ return -1.0; } run_long_program(); finish = clock(); if (finish = (clock_t)(-1)){ return -1.0; } seconds = (double) (finish-start)/CLOCKS_PER_SEC; return seconds; } |
When appropriate one should also check for overflow in seconds. The key, though, is that because the proper function is being called and a reasonable value will result. This function will correctly return the time in seconds.
Credits/Interesting Links:
...