Updating a clock to display the correct time is actually difficult and involved, sleep(1) will not work! The problem reminds me of this Intel article on syncing video output [1]
Basically, sleep(1) won't always align with clock updates, so sometimes a given time will display for more or less time than a second. This can be observed by opening the clock widget on Windows XP for example, it's very noticeable. I don't actually know a nice way to do it, maybe updating 10 times per second or so?
On POSIX systems, clock_nanosleep() can accept an absolute time argument.
// In a real program one would probably not use time()
// Also, some older pre-release versions of the realtime
// kernel patches had the clock_nanosleep() and time()
// clocks out of sync by 0.5s (IIRC)
for(;;) {
struct timespec after_epoch = { .tv_sec = time(NULL) + 1, .tv_nsec = 0 };
// Check for EINTR in a real program
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &after_epoch, NULL);
printf("Tick\n");
}
Rather useful in this case could be an adaptive method. First, you update every 50ms until you circled in the moment when the second toggles. Then you can do sleep(1) again and save resources.
Alternatively, use time() to only sleep the remaining timespan until the next second.
Basically, sleep(1) won't always align with clock updates, so sometimes a given time will display for more or less time than a second. This can be observed by opening the clock widget on Windows XP for example, it's very noticeable. I don't actually know a nice way to do it, maybe updating 10 times per second or so?
[1] http://software.intel.com/en-us/articles/video-frame-display... - it's down right now, one of the diagrams illustrates the problem well though: http://software.intel.com/file/3984