Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of CLOCKS_PER_SEC

Tags:

c++

types

time

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.

like image 293
Maxpm Avatar asked May 25 '11 18:05

Maxpm


1 Answers

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.

like image 80
Michael Burr Avatar answered Sep 21 '22 07:09

Michael Burr