Why does an empty loop use so much processor time?

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

    A cpu can do some billion operations per second. This means the empty loop runs mybe one million times per second. The loop with the sleep statement runs only 1000 times per second. In this case the cpu has some operations per second left to do other things.

    Say we have a 3GHz cpu. 3Ghz = 3 000 000 000Hz - The cpu can run the loop three bilion times a second (simplyfied).

    With the sleep statement the loop is executed 1000 times a second. This means the cpu load is

    1000 / 3 000 000 000 * 100 = 0.0001%

提交回复
热议问题