There are a couple of other similar questions on SO, but none of them have satisfactory/relevant answers.
I have a single threaded C++ program which does something essentially like this:
while(true) {
//do things which are cpu bound
}
The problem is that when I run this program it is usually the only process on my whole computer that is doing active work.
With nothing else to schedule, the OS naturally schedules this program heavily and my CPU usage shoots through the roof, which I do not want. Naturally, my fan starts whirring too which is especially annoying.
The way I am combating this is to add sleep(100)
inside the loop (this is fine in terms of correctness for me), but while it works, it annoys me that it's not the technically correct solution.
This is because if I wanted to sleep for a very accurate amount of time and I had lots of other processes running on my computer this would not be a good solution, as sleep
is not accurate and it also doesn't allow other processes to use the CPU while my program is still scheduled - but this is not my real problem.
What would be the correct solution to reduce CPU usage without using sleep
, assuming this is the only program that is actively running?