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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.