Why does an empty loop use so much processor time?

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

    Because that would run instructions all the time.

    Normal programs don't madly run instructions all the time.

    For instance, GUI programs just sit idle waiting for events, (such as keyboard input),

    Note: sitting idle != while(true);

    They only run instructions when events arrive, and the event-handling code is usually small and runs very quickly, (otherwise, the program will appear to be not-responding). Imagine your app gets 5 keystrokes per second, how much CPU time would it take?

    That's why normal processes don't take that much CPU.

    Now, earlier I said that sitting idle is not the same as an infinite empty loop. Why is that? Sitting idle means telling the OS that you don't have anything to run.

    An infinite loops actually is something to run (a repeating jump instruction).

    On the other hand, having nothing to run means basically that the OS won't even bother giving you any processor time at all, even if it's your turn.

    Another example where programs sit idle is loading files: when you need to load a file, you basically send a signal to the disk and wait for it to find the data and load it into memory. While the data is being loaded (several milliseconds), the process just sits idle, doing nothing.

    Yet another instance of a process sitting idle, is Sleep(1), here it's explicitly telling the OS not to give it any cpu-time before the specified time has passed.

提交回复
热议问题