Jeffrey
Jeffrey

Reputation: 1689

Why does an empty infinite loop use my whole CPU?

I'm running a simple infinite loop in C++:

int main() {
  for (;;) {}
}

and when I compile and run it, the program consumes 100% of my CPU. Why does this happen? I'm using g++ 4.7 on a Macbook Pro.

Upvotes: 3

Views: 1397

Answers (2)

NickV
NickV

Reputation: 1646

If you take a quick look at the assembly you will see:

.L2:
    jmp     .L2
    .cfi_endproc

So the compiler generated a jump instruction. The CPU just does what it is instructed to: jump around. You could ask why the compiler generated this code.

Repro:

gcc -S test.c -o test.s; more test.s

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 992847

CPUs run the code they are given as fast as they can. If there is nothing much else of interest going on, the OS will give as much CPU time as possible to the process that wants it. If you were to run two of these processes at the same time, they would each get roughly 50% of the CPU time. (Note that the terms used to describe CPU usage get a bit fuzzy if you have more than one core, as virtually all modern CPUs do. If you have a quad core system, the above loop would take 100% of one core, or 25% overall.)

Compute-bound programs that do not do I/O (or otherwise wait for anything external) all behave in this same way.

Upvotes: 11

Related Questions