Another thing to note is when you call sleep with a low value it may decide not to sleep at all, so this loop just might be constantly doing syscalls in a tight loop.
You can trivially verify it by running the following, I have personally been using "sleep for 1ms in a loop to prevent CPU burn" for years and never noticed it having any impact, it's not until I go into microseconds when I can start noticing my CPU doing more busy work.
// g++ -std=c++20 -osleep sleep.cpp
#include <thread>
#include <chrono>
int main(int, char **)
{
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds {1});
}
return 0;
}
> Another thing to note is when you call sleep with a low value it may decide not to sleep at all, so this loop just might be constantly doing syscalls in a tight loop.On what system? AFAIK, if your sleep time is low enough, it will round up to whatever is the OS clock resolution multiple, not skip the sleep call completely. On Linux, it will use nanosleep(2) and I cannot see any mention of the sleep not suspending the thread at all with low values.
At any rate, back to the code at hand, there are many ways to block on SIGINT without polling. But it's also hugely odd that this code does not read events from the X11 socket while it does so. This is code smell, and a poorly behaved X client.
https://lxr.linux.no/#linux+v6.7.1/kernel/time/hrtimer.c#L20...
https://www.man7.org/linux/man-pages/man2/PR_SET_TIMERSLACK....
I'd love to see numbers with a Kill-A-watt between the PC and the wall
This was changed sometimes in the last 20 years, probably with battery powered devices becoming more prevalent and CPUs implementing more advanced sleep states.
1. https://people.kernel.org/joelfernandes/on-workings-of-hrtim...
import time
while True:
time.sleep(0.001)
also the script itself it bounces between 0% and 1% cpu usage