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..");
}
}
}
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).
After iterating 30-60 000 times when running the AskScript program (below) node process consumed up to 2GB of RAM.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With