Type CLOCKS_PER_SEC

What data type CLOCKS_PER_SEC is usually represented as? long unsigned int ? clock_t ? Does it differ from implementation to implementation?

I ask because I use CLOCKS_PER_SEC in the return value, and I want to make sure that I use the most suitable type.

+7
source share
3 answers

All that the C promises standard is that CLOCKS_PER_SEC is a constant expression with type clock_t , which must be an arithmetic type (can be an integer or a floating type).

(C99 7.23 Date and time <time.h> )

I think that clock_t usually long , but I would not put in my life that I am right.

My usually faithful Harbison and Steele (3rd ed.) clock_t using clock_t to double for use in your programs so that your code can work regardless of the actual clock_t type (18.1 CLOCK, CLOCK_T, CLOCKS_PER_SEC, TIMES)

Here's how the clock function can use ANSI C:

 #include <time.h> clock_t start, finish, duration; start = clock(); process(); finish = clock(); printf("process() took %f seconds to execute\n", ((double) (finish - start)) / CLOCKS_PER_SEC ); 

Notice how the cast type double allows clock_t and CLOCKS_PER_SEC be either a floating point or an integral.

You may be wondering if this will work for your purposes.

+7
source

CLOCKS_PER_SEC is a macro that usually expands to a literal.

glibc manual says:

In the GNU system, clock_t is the equivalent of long ints and CLOCKS_PER_SEC is an integer value. But on other systems, both clock_t and the macro type CLOCKS_PER_SEC can be integer or floating point. Casting processor time values ​​are doubled, as in the above example, make sure that operations such as arithmetic and printing work correctly and no matter what the underlying representation.

+3
source

CLOCK_PER_SEC is actually defined by POSIX as part of the time.h header.

This suggests that clock_t is described by sys / types.h .

This, in turn, reads:

time_t and clock_t must be integer or real floating types.

So, all that you can assume in portable code is that it is an integer or a floating point. If you just need to declare a variable to hold the value, declare it as "clock_t".

+1
source

All Articles