Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CPU usage increases for Empty Infinite While loop

Can anyone explain me why the following Infinite loop takes a lot of CPU usage (CPU usage has increased upto 50% if total core is 2 and 100% if total CPU core is just 1)

But if I un-comment the line it reduces to 1 or 2 CPU usage?

    public class Program
    {
        public static void Main(string[] args)
        {
            while (true)
            {
                //Console.WriteLine("hello..");
            }
        }
    }
like image 715
Santosh Panda Avatar asked Jul 31 '14 04:07

Santosh Panda


People also ask

Does while loop consume CPU?

It consumes all CPU it can get, unless... The loop body is trivial, and optimised away. The loop contains a blocking operation (like a file or network operation).

Does while loop consume memory?

After iterating 30-60 000 times when running the AskScript program (below) node process consumed up to 2GB of RAM.

How can CPU usage exceeds 100?

Multiple instances of a service running on one server or in a multi-core environment can produce CPU usage percentages well above 100%. If you upgrade from a dual processor to a quad processor under the same architecture, you should see roughly the same CPU numbers for the same loads and applications.


1 Answers

Console.WriteLine is a blocking (interruptable) I/O call, so other things can happen while the processor is blocked on I/O. In fact, it spends significantly more time blocked on I/O than it does evaluating the trivial condition true and jumping!

Without the writeline call, your processor is completely busy and cannot be interrupted.

Try replacing Console.WriteLine with something like int x = 1, or anything that does not block. This should behave like the empty body case.

like image 111
Ray Toal Avatar answered Nov 04 '22 10:11

Ray Toal