Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an empty loop use so much processor time?

Tags:

c++

c

If I have an empty while loop in my code such as:

while(true);

It will drive the processor usage up to about 25%. However if I do the following:

while(true)
    Sleep(1);

It will only use about 1%.

So why is that?

Update: Thanks for all the great replies, but I guess I really should have asked this question, What's the algorithm behind sleep()? which is more of want I wanted to know.

like image 242
paul Avatar asked Oct 23 '09 23:10

paul


2 Answers

With the former, the condition true must be checked by the processor as often as the application can possibly get focus. As soon as the application gets processor attention, it checks true, just like any other loop condition, to see if the next instruction in the loop can be executed. Of course, the next instruction in the loop is also true. Basically, you are forcing the processor to constantly determine whether or not true is true, which, although trivial, when performed constantly bogs the processor down.

In the latter, the processor checks true once, and then executes the next statement. In this case, that is a 1ms wait. Since 1 ms is far greater than the amount of time required to check true, and the processor knows it can do other things during this wait, you free up a lot of power.

like image 120
JoshJordan Avatar answered Sep 30 '22 18:09

JoshJordan


I am going to guess that you have four cores on your multicore processor, which would explain the 25%, as you are completely tying up one processor doing your busy loop, as the only break in it is when the application is delayed so another application can run (but that may not happen depending on the load).

When you put a thread to sleep then it allows the OS to do other operations, and it knows when, as a minimum, to come back and wake up the thread, so it can continue it's work.

like image 43
James Black Avatar answered Sep 30 '22 19:09

James Black