Issue
while (true) {
sleep(seconds(1));
log(get_current_time());
}
This question isn't specific to any one language.
Is it possible to guarantee that this thread records log entries exactly one second apart? From what I understand, after 1 second of sleep, the thread will be woken up and marked as runnable in the kernel but depending on which other threads are runnable and their relative priorities (or perhaps other busy work that must be done), the kernel may not schedule the thread to run until a small amount of time after. This may cause the log entries to be 1.1 seconds apart.
Can anything be done in user-level code to reduce this variance? Besides just having as few other threads as possible.
Solution
Depends what you mean by "exactly." No clock can ever be "exact." and sleep(1)
only guarantees to sleep for at least one second. It could sleep longer, but on modern Linux, probably only a tiny bit longer.
If what you really want is, for the long-term average number of iterations to be one per second, then you need to do this (pseudo-code because I don't have access to a real computer right now):
dueDate = get_current_time();
while (true) {
sleepInterval = dueDate - get_current_time();
if (sleepInterval > 0) {
sleep(sleepInterval);
}
doWhateverNeedsToBeDone();
dueDate += oneSecond;
}
This prevents errors in the timing from accumulating. The sleep()
call might not wake at exactly the right time, but the next dueDate
always is incremented by exactly one second.
It helps if your get_current_time()
-like function and your sleep()
-like function both work on a fine grain. Linux has clocks that return time in nanoseconds, and it has the ability to sleep for a given number of nanoseconds, but I forget the actual names of those functions. You can find them easily enough in Google.
If that trick doesn't give you enough accuracy using regular Linux system calls, then you may need to run a "real-time" enabled version of Linux, and use priviliged system calls to enable real-time scheduling for your process.
Answered By - Solomon Slow Answer Checked By - Marie Seifert (WPSolving Admin)