Reputation: 25592
What datatype is CLOCKS_PER_SEC typically represented as? long unsigned int
? clock_t
? Does it vary from implementation 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.
Upvotes: 8
Views: 7401
Reputation: 340316
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
allowsclock_t
andCLOCKS_PER_SEC
to be either floating-point or integral.
You might consider whether this would work for your purposes.
Upvotes: 8
Reputation: 71555
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".
Upvotes: 1
Reputation: 385274
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.
Upvotes: 3