Cpu usage

Hi all,

When I have a below while loop in my code (This observation is same for C and Perl)

i= 0;
while(1)
{
i++;
}

for above the CPU uses goes beyond 49% on hp-ux machine, why cpu usage increase at this level for just a simple while loop?

and if I have a single print statement (as shown below) under this while then cpu usage decrease and comes at normal level i.e. 0.9 or 1%

i= 0;
while(1)
{
i++;
printf("%d\n", i);

}
Also adding few mili seconds sleep inside the while loop results reducing the CPU usage

any idea why it happens and how we can avoid the CPU usage?

Thanks....

Your while loop does nothing but compute. It tries to use as much cpu as it can get. Outputing some data and sleeping do not use the cpu. I don't understand why you find any of this confusing.

As for avoiding cpu usage, you actually show two ways to do this. I don't understand why you then pose the question.

But there is nothing wrong with using the cpu if that is what your program needs to do. It's the kernel's job to ensure that all processes are allowed to run. The kernel will limit your process' cpu usage as it needs to. In general, a cpu bound process can hog the cpu for a few seconds, but its priority will be worsened as a result. It soon will have to least priority of any process and will find itself running only when the kernel can't find anything else to do.

At most, the only thing you need to do is to consider adding a nice() call like this:
nice(5);
This is a clue to the kernel to lower your process' priority.

You should have asked that question instead "Why isn't the CPU load 100% with that loop" and the answer would have been "Because your process is single threaded while your OS has 2 CPUs available and no other process significantly load the system".

With the printf statement added, the process is no more CPU bounded but I/O bounded. The reason why the CPU load is much slower.