EDIT: I felt this answer was incomplete, because it does not answer your actual question. The first part now explains why your approach fails, the second part is about how to solve your problem in a better way.
You are using clock()
in a way, where you wait for a number of specific points in time. Due to the nature of clock()
and the limited precision of float
, your check basically is equivalent to saying: Are we in a window [x-eps, x+eps]
, where x
is a multiple of 5
and eps
is generally small and depends on the floating point type used and how big (clock() - start)
is. A way to increase eps
is to add a constant like 1e6
to (clock() - start)
. If floating point numbers were precise, that should not affect your logic, because 1e6
is a multiple of 5
, but in fact it will do so drastically.
On a fast machine, that condition can be true multiple times every 5 seconds; on a slow machine it may not be true every time 5 seconds passed.
The correct way to implement it is below; but if you wanted to do it using a polling approach (like you do currently), you would have to increment start by 5 * CLOCKS_PER_SECOND in your if
-block and change the condition to something like (clock() - start) / CLOCKS_PER_SECOND >= 5
.
Apart from the clock()
-specific issues that you have, I want to remind you that it measures CPU time or ticks and is hardly a reliable way to measure wall time. Fortunately, in modern C++, we have std::chrono
:
auto t = std::chrono::steady_clock::now();
auto end = t + std::chrono::seconds( 10 );
while( t < end )
{
t += std::chrono::seconds( 5 );
std::this_thread::sleep_until( t );
std::cout << ( rand() % 10 + 1 ) << std::endl;
}
I also highly recommend replacing rand()
with the more modern tools in <random>
, e.g.:
std::random_device rd; // Hopefully a good source of entropy; used for seeding.
std::default_random_engine gen( rd() ); // Faster pseudo-random source.
std::uniform_int_distribution<> dist( 1, 10 ); // Specify the kind of random stuff that you want.
int random = dist( gen ); // equivalent to rand() % 10 + 1.