Sunday, October 29, 2017

Windows timer resolution: the nuclear option

Windows timers are a mess to deal with from programmer's perspective - a program can't schedule a sleep or a wait with less than 15ms granularity (resolution). This applies to all kinds of waiting, whether for a network socket, or just plain sleeping for an interval. All intervals[1] are rounded up toward the next multiple of 15ms.

Then again, Windows has an API to increase the timer resolution, allowing for as little as half a millisecond granularity. Thing is, this resolution is global and affects all CPUs, apps and services alike. This affects battery life for laptops, and power consumption in general. It also lowers system performance[2].

The issue's been documented[6] for a long time, but Spotify[3] or Chrome[4][5] developers don't give a slightest fuck.

Scroll to the bottom of the post. There's a better solution available in bold letters.

We can create wrapper DLLs and insert them in programs' directories, but there are problems. First off, auto-updating apps like Chrome will silently re-create their program directories, losing the wrapper. Second, some apps use Windows manifests that force usage of the system-provided version.

However, there comes the Nuclear Option.

Bet you heard of assembly language. Old people write in it and it's scary. But don't worry, it only takes the bare minimum of x86 knowledge to fix the mess with strategic nuclear bombing.


Before:
 

After:


Then, I went to c:/windows/syswow64. That directory has all the system libraries in it. While you can't delete a dll that's in use, you can rename it. Hence I renamed winmm.dll to _winmm_orig.dll. My modified version went under the original name.

During the reboot I expected the OS to catch fire. Wrong. Spotify runs without the implied nastiness.

However, there's a sure-fire solution with no chance for OS breakage. See <https://github.com/rustyx/nobuzz>.

[1] Except for intervals of zero and one millisecond - each does something special.
[2] I don't have benchmarks on hand. But just imagine each context switch invalidating CPU cache. Also note that Windows bounces processes between cores for some stupid reason. That also fucks up the cache.
[3] It sets the timer interval for the entire duration it's run, regardless of whether it plays music or not.

No comments:

Post a Comment