std::chrono vs timer coalescing in macOS

Recently I needed to call a function in the background of a C++ program periodically. I decided to use the STL for the task.

During research, I found a nice article about periodic processing with C++11. The sample code has helped me to quickly put together a solution for my project. However, I noticed that the author was showing average wakeup errors of 20 microseconds on Windows and 96 microseconds on Linux. Running the sample code on macOS yielded errors of up to 2000 microseconds! That is a big margin. I was a little disappointed. My favorite OS is getting worse results… oh no.

But then I remembered that newer versions of macOS employ “timer coalescing“, which tries to save energy by reducing timer accuracy and “bundling” wakeups together to let the CPU sleep for longer periods of time.

Nice, but thankfuly we can turn it off for more accurate testing:

sudo sysctl -w kern.timer.coalescing_enabled=0

After that the errors went down to about 40 microseconds on average. I have yet to look up the proper way to tell the OS that my app needs this, regardless of the global setting, but my curiosity is satisfied for now.

Note: the source code from the article is only provided as a PDF from which it is hard to extract in a usable form, so I took the liberty to make a plain-text copy on Github.