开发者

Why does a busy loop take 100% of the CPU?

Why does a busy loop often uses 100% of the cpu time while loops that implement complex algorithms开发者_如何学C would use much much less?

thanks :)


JUMP instructions in the CPU architecture are inefficient because they cause the pipeline to flush. A busy loop is effectively an infinite series of JUMP instructions.


A complex algorithm can certainly use 100% of the cpu. However, many loops that implement complex algorithms either explicitly yield the thread periodically and/or have some code that calls down into the OS at some point, where either the thread is yielded or something that requires a wait (such as calling on a co-processor) happens.


First, if your busy loop uses 100% then you aren't doing it right. Sleep for a bit.

Second, complex algorithms often involve memory to store values as opposed to just looping. Any time the thread needs to use an external resource like memory, disk, etc. the CPU has to wait a bit. This is why you would see it use less than 100%.


A "busy loop" does not have to talk to memory, so the CPU is basically doing all work itself without waiting for external input.


Depends what that "complex algorithm" is doing. Does it do Hard Drive access? Network requests? Interact with any other hardware? When that happens the CPU will have to wait for those things to complete, so it sits around doing nothing (or does a context switch to some other work) while it waits for that information to come back.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜