Why does a busy loop take 100% of the CPU?
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.
精彩评论