102 points · by nikbackm · 6y ago · 93 comments
- Slack (sometimes) sets the global timer to 1ms when it is in the foreground, but restores it in background
- Spotify sets the global timer to 1ms, no matter what. Even if it isn't playing.
- Skype sets 1ms, if started at Startup (which it defaults to), even though I am logged out and it just has a tray icon. But when I manually start it, it doesn't (always) set it to 1ms.
- VSCode will set it to 1ms when you are interacting with it, but will eventually revert to 15.6ms if left alone (even if it is still in foreground).
- Firefox doesn't appear to set it (on its own; I presume that if I opened a tab that was using a low setTimeout or requestAnimFrame it might).
Spotify is interesting. A lot of people probably have that app, and since it sets 1ms unconditionally, it would have been setting fast-timer mode prior to the 2004 update, which could inadvertently "speed up" whatever games people were running.
That includes my own game, which uses a foreground sleep of as low as 1ms to try to hit its time target, and I don't call timeBeginPeriod. I guess I'll find out when I get the 2004 update.
Yup, I wrote such a (small, freeware) game 15+ years ago. I wasn't aware of timeBeginPeriod at the time, but I observed that for some inexplicable reason, the game ran more smoothly when Winamp was running in the background. :-)
Our models of computer timers are woefully inadequate. These things execute billions of instructions per second. Why shouldn't we be able to schedule a timer at sub-millisecond resolution?
Answer: we can. But the APIs are very old and assume conditions no longer present. Or something like that. Anyway, they don't get the job done.
Everybody seems to start a hardware timer at some regular period, then simulate 'timer interrupts' for applications off that timer's interrupt. If you want 12.5ms but the ol' ticker is ticking at 1ms intervals, you get 13 or so depending on where in an interval you asked, it could be 12.
Even if nobody is using the timer, its ticking away wasting CPU time. So the tendency is, to make the period as long as possible without pissing everybody off.
Even back in the 1980's, I worked on an OS running on the 8086 with a service called PIT (Programmable Interval Timer). You said what interval you wanted; it programmed the hardware timer for that. If it was already running, and your interval was shorter than what remained, it would reprogram it for your short time, then when it went off it reprogrammed it for the remainder.
It kept a whole chain of scheduled expirations sorted by time. When the interrupt occurred it'd call the callback of the 1st entry and discard it. Then it'd reprogram the timer for the remaining time on the next.
It took into account the time of the callback; the time to take the interrupt and reprogram. And it achieved sub-millisecond scheduling even back on that old sad hardware.
And when nobody was using the timer, it didn't run! Zero wasted CPU.
Imagine how precise timers could be today, on our super duper gigahertz hardware.
But what do we get? We get broken, laggy, high-latency, late timer callbacks at some abominable minimum period. Sigh.
</rant>
The problem is that what you describe is very hard to guarantee in a non-realtime OS. Modern CPUs are pretty damn fast, that's true, but they can't task switch on a dime. The delay between an IRQ being triggered and task being scheduled can vary pretty wildly, especially if the CPU is already under a heavy load.
You can still try your luck with nanosleep() and see how that treats you. It might work. It probably won't always work.
In general if you need to react so fast on some event you probably want to avoid polling at all costs. That's why most OSs are fine relaxing timer constraints for better overall performance. If you can't react on an external interrupt and you really need to be reactive busy-polling is still probably your best bet.
it's not just the API, the whole operating system need to be aware of the need to operate at such frequency, because even if the clocks are faster, the software gets interrupted all the time. what good would a nanosecond api do if an interrupt can stall the cpu for a microsecond?
hence the need for a whole class of realtime operating systems. the next question would then be, why aren't all computers using a realtime operating system? because with the relaxed time constraints we get great returns in speed and cost.
What I want to say is that we already have precise timers usable on modern hardware; as for why Windows doesn't use that properly, I have no idea, but I can guess that's some technical debt in the scheduler.
[1] https://www.kernel.org/doc/ols/2006/ols2006v1-pages-333-346....
I feel your frustration.
(For those about to suggest how it should have been done, the application also stored an atomic revision counter, so the unit test was switched to that instead of a timestamp.)
https://docs.microsoft.com/en-us/windows/win32/api/sysinfoap...
The lack of information and response from Microsoft on this has been quite frustrating.
Win10 2004 timer changes are breaking.
Timer frequency adjustments (timeBeginPeriod) don't seem to affect Windows timers in the same process like they used to do!
Again. In Win10 2004, if you do timeBeginPeriod(1), timers in the same process (other than using the deprecated multimedia timer) seem to only trigger every 15-16 ms or so instead of 1 ms.
This is bad.
As a sidenote about Win10 2004, after timeBeginPeriod(1), Sleep(1) seems to take about 2 ms per call. Or at least it seems to take about 1950 ms to call Sleep(1) 1000 times when I tested it. Confusing.
There is an a ticket opened in the `Feedback Hub` app for it that I've been checking but there seems to be no acknowledgement from Microsoft about this, which is one of the more annoying aspects.
That's when I discovered that doing a "process more data if there is any, if not - sleep(1)" loop is a very bad way of doing it, as on Windows Server 2016 "sleep(1)" means "sleep 16ms". It all worked fine once the timer resolution was changed to 1ms, but yeah, the default value will screw you over if you have anything this time sensitive and are using sleeps or waits on windows.
If you don't want two of the process running at once for any reason, a check-do-sleep loop can be easier to reason than debouncing an interrupt based approach. Less efficient, but often efficient enough especially if you are just throwing something together quickly with a view to if being PoC or a temporary utility.
So no one would rely on Sleep for periodicity. Getting reliable timing performance out of Windows is... challenging.
So ultimately it's just simpler to talk about Sleep. Windows developers who have to deal with it understand that same mechanism (which used to be determined by the global timer frequency, which you could adjust by calling timeBeginPeriod) affects all of the different timers.
Really? On versions prior to 20H2? This gives me 16ms resolution for SetWaitableTimer but 1ms for timeSetEvent:
#include <tchar.h>
#include <Windows.h>
#include <MMSystem.h>
#pragma comment(lib, "winmm.lib")
static unsigned int prev_time = timeGetTime();
VOID CALLBACK callback(LPVOID lpArgToCompletionRoutine, DWORD dwTimerLowValue, DWORD dwTimerHighValue)
{ unsigned int now = timeGetTime(); _tprintf(_T("%u\n"), now - prev_time); prev_time = now; }
void CALLBACK callback(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) { return callback(NULL, 0, 0); }
int _tmain(int argc, TCHAR *argv[])
{
enum { msec = 1 };
HANDLE handle = CreateWaitableTimer(NULL, FALSE, NULL);
LARGE_INTEGER due = {};
SetWaitableTimer(handle, &due, msec, callback, NULL, FALSE);
for (int i = 0; SleepEx(100, TRUE) == WAIT_IO_COMPLETION && i < 30; ++i) { }
CloseHandle(handle);
MMRESULT id = timeSetEvent(msec, 1, callback, NULL, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);
Sleep(100);
timeKillEvent(id);
}You sure? According to e.g. the article it results in "sleep anywhere between 1 and 16mSec". But this illustrates part of the problem here: arguably problematic use of Sleep() where other solutions are more appropriate and people not reading the documentation and/or not realizing what it means.
[1] https://developercommunity.visualstudio.com/content/problem/...
In my opinion this still remains the conclusion, as it has been for the past decades. I cannot remember when I read a bit on Sleep() behavior and timeBeginPeriod() but I remember that what I read was enough to make clear you just shouldn't rely on these (unless you're 100% sure the consequences are within your spec and will remain so), also not because the workarounds are also widely known (IIRC - things like using WaitForSingleObject if you need accurate Sleep).
You won't get any more timing accuracy with WFSO.
"Windows 10" is too much of a moving target, and it's about time Microsoft stopped trying to pretend to the public that it's all one operating system. If they're not going to usefully document potentially breaking changes, they should at least do us all the courtesy of bundling these changes up into a release that increments the major version number, and gives us the option of not upgrading for a few years instead of having the software as a service model forced upon us.
(Given what I've written above, it probably won't surprise you to find out I recently spent a decent chunk of time trying to find a workaround for a different undocumented change brought by Windows 10 version 2004).
Any chance you could share this so those of us who haven't dealt with it yet might have a heads-up?
Shouldn't this at least be per-core rather than global? Then most cores can keep scheduling at a low tick rate and only one or two have to take care of the jittery processes.
Like it might be much (even 1000x) slower to read QueryPerformanceCounter due to cross-CPU synchronization issues.
Seems like a good move to me - just a bit of a shame a few applications might break.
Why does it require that? Timeouts should normally be on the order of minutes. Why does Chrome need timer interrupts to happen many times per second?