开发者

Type of CLOCKS_PER_SEC

What datatype is CLOCKS_PER_SEC typically represented as? long unsigned int? clock_t? Does it vary from implemen开发者_开发百科tation to implementation?

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


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

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

I think that clock_t is typically a long, but I wouldn't bet my life that I'm right.

My usually trusty Harbison & Steele (3rd ed) suggests casting clock_t to double for use in your programs so your code can work regardless of the actual clock_t type (18.1 CLOCK, CLOCK_T, CLOCKS_PER_SEC, TIMES):

Here is how the clock function can be used to time an ANSI C program:

#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 );

Note how the cast to type double allows clock_t and CLOCKS_PER_SEC to be either floating-point or integral.

You might consider whether this would work for your purposes.


CLOCKS_PER_SEC is a macro, that usually expands to a literal.

The glibc manual says:

In the GNU system, clock_t is equivalent to long int and CLOCKS_PER_SEC is an integer value. But in other systems, both clock_t and the type of the macro CLOCKS_PER_SEC can be either integer or floating-point types. Casting processor time values to double, as in the example above, makes sure that operations such as arithmetic and printing work properly and consistently no matter what the underlying representation is.


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

That says it's a clock_t as described by sys/types.h.

That in turn says:

time_t and clock_t shall be integer or real-floating types.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜