Why does an empty loop use so much processor time?

前端 未结 12 2473
小鲜肉
小鲜肉 2021-02-13 15:05

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 followin

12条回答
  •  囚心锁ツ
    2021-02-13 15:23

    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.

提交回复
热议问题