If you want a portable solution, you shouldn't expect high-precision timing. Usually, you only get that with a platform-dependent solution.
A portable (albeit not very CPU-efficient, nor particularly elegant) solution might make use of a function similar to this:
#include <ctime>
void wait_until_next_second()
{
time_t before = time(0);
while (difftime(time(0), before) < 1);
}
You'd then use this in your function like this:
int min5()
{
wait_until_next_second(); // synchronization (optional), so that the first
// subsequent call will not take less than 1 sec.
...
do
{
wait_until_next_second(); // waits approx. one second
while (...)
{
...
}
} while (...)
}
Some further comments on your code:
Your code gets into an endless loop once minute
reaches the value 5.
Are you aware that 00
denotes an octal (radix 8) number (due to the leading zero)? It doesn't matter in this case, but be careful with numbers such as 017
. This is decimal 15, not 17!
You could incorporate the seconds++
right into the while
loop's condition: while (seconds++ <= 59) ...
I think in this case, it would be better to insert endl
into the cout
stream, since that will flush it, while inserting "\n"
won't flush the stream. It doesn't truly matter here, but your intent seems to be to always see the current time on cout
; if you don't flush the stream, you're not actually guaranteed to see the time message immediately.