Question

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 #defined (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"?

Was it helpful?

Solution

What happens when you overflow a signed integral type is implementation defined, and could be a signal. And yes, this means that clock() can only be used for a fixed length of time after the start of your process, and probably only then if the implementation ensures that the first call will always return 0 (the case on all implementations I know of).

OTHER TIPS

If clock_t is defined as a signed type, then yes, that is the expected behavior.

If you're concerned about wrap-around, you could always cast the clock_t value to an unsigned long (which means you're assuming that clock_t is no wider than a long), and store/compare that value instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top