Santosh Panda
Santosh Panda

Reputation: 7341

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..");
            }
        }
    }

Upvotes: 7

Views: 5113

Answers (4)

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

The reason is because your CPU cannot do anything else while it's executing that loop. The CPU is not aware that the infinite loop isn't a complicated calculation that just requires a lot of iterations. Hence it keeps on evaluating that true condition infintely resulting in consumption of increase CPU usage.

You may also like to check Halt and Catch Fire

On a side note:

If you want to avoid the infinity loop then you can simply use a WaitHandle. To let the process be exited from the outer world use a EventWaitHandle with a unique string.

Upvotes: 2

vikstous
vikstous

Reputation: 21

When the line is commented out the while loop does nothing and just consumes CPU spinning in a circle. When you call WriteLine your program makes a call to the operating system which suspends your process temporarily. This leads to your program being "blocked" for most of the time and consuming CPU only between write() system calls.

Upvotes: 2

Ray Toal
Ray Toal

Reputation: 88388

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.

Upvotes: 7

Randall Cook
Randall Cook

Reputation: 6776

The CPU spends all its time checking that true is true, and the compiler didn't optimize it away. With the WriteLine, the process can block when writing to the console, which reduces overall CPU usage.

Upvotes: 2

Related Questions