Why does an empty loop use so much processor time?

前端 未结 12 2506
小鲜肉
小鲜肉 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:20

    You have a quad-core machine, am I right? If so,

    while(true);
    

    is actually using 100% of one of your cores.

    To the operating system, it seems your program has a lot of work to do. So the operating system lets the program go ahead with this work. It can't tell the difference between your program number crunching like crazy, and doing a useless infinite loop.

    Sleep(1);
    

    on the other hand explicitly tells the operating system that your have no work to do for the next millisecond. The OS will thus stop running your program and let other programs do work.

提交回复
热议问题