Question regarding clock tick count generated by clock()
from <ctime>
. (Usage of clock()
is covered in other questions)
On my system clock_t
is an alias for long
whose max value according to my compiler's <climits>
is 2147483647.
clock_t delay = clock_t(10) * CLOCKS_PER_SEC;
clock_t start = clock();
while(clock() - start < delay); //Note Semi-colon here makes this null statement
std::cout << clock();
Running this I get roughly 10060. Which is consistent with CLOCKS_PER_SEC
being #define
d (for my system) as 1000.
So if there's 1000 CLOCKS_PER_SEC
then 2147483647 / 1000 = 2147483.647 seconds, which works out to be roughly 24-25 days.
I'm not sure if it's actually defined behavior by C++, but I note that common behavior of exceeding the long
limit is to wrap to the negative end.
For example,
long m = long(2147483647);
std::cout << ++m << std::endl;
Would output: -2147483648
So suppose the program had been running for a long time before initializing start
, and start
happened to be initialized to 2147483647 (max possible long
value).
At this point, I'd assume we'd start wrapping on values returned by clock()
so getting values such as -2147482649 as we are approaching 2147483647 again.
So now my original code would probably take a very long time to complete the loop, much longer than the delay intended.
Is the the actual behavior? Should this style pause only be used for delays less than a certain amount? Is there some other check that ought be made to make this "safe"?