Depends on what system you are on. It may use a 32+ or a 64-bit clock_t
. It will definitely roll over, but if it's 64-bit, it will be OK for quite some time before it rolls over - 264 microseconds is still an awful long time (approx 244 seconds, and there is around 216 seconds per day, so 228 days - which is about 220, or a million, years... ;)
Of course, in a 32-bit system, we have about 212=4096 seconds at microsecond resoltion. An hour being 3600s = about 1h10m.
However, another problem, in some systems, is that clock()
returns CPU time used, so if you sleep, it won't count as time in clock()
.
And of course, even though CLOCKS_PER_SEC
may be 1000000, it doesn't mean that you get microsecond resultion - in many systems, it "jumps" 10000 units at a time.
In summary, "probably a bad idea".
If you have C++11 on the system, use std::chrono
, which has several options for timekeeping that are sufficiently good for most purposes (but do study the std::chrono
docs)
Example code:
#include <iostream>
#include <chrono>
#include <unistd.h> // replace with "windows.h" if needed.
int main()
{
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
// 10 seconds on a unix system. Sleep(10000) on windows will be the same thing
sleep(10);
end = std::chrono::system_clock::now();
int elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>
(end-start).count();
std::cout << "elapsed time: " << elapsed_seconds << "s\n";
}