Does anything look wrong in my code?
Several things look wrong. The first is stdout
line buffering - see eduffy's answer for that.
The second problem is that you're doing sec++; sleep(1000);
, which means that sec
will be incremented once every 1000 seconds or more.
The third problem is that if(sec == 59;
is wrong and needs to be if(sec == 60)
. Otherwise you'll have 59 seconds per minute.
The fourth problem is that sleep(1)
will sleep for at least 1 second, but may sleep for 2 seconds, or 10 seconds, or 1234 seconds. To guard against this you want something more like this:
expiry = now() + delay;
while(true) {
sleep(expiry - now() ):
expiry += delay;
}
The basic idea being that if one sleep takes too long then the next sleep will sleep less; and it'll end up being "correct on average".
The last problem is that sleep()
doesn't really have enough precision. For 1 second delays you want to be able to sleep for fractions of a second (e.g. like maybe 9/10ths of a second). Depending on which compiler for which OS, there's probably something better you can use (e.g. maybe nanosleep()
). Sadly there may be nothing that's actually good (e.g. some sort of "nanosleep_until(expiry_time)
" that prevents jitter caused by IRQs and/or task switches that occur after you determine now
but before you call something like "nanosleep()
").