How is the percentage of CPU usage calculated?

In my Ubuntu 12.04, with psensor, I saw a percentage number updated for cpu usage. I wonder how this percentage caculated? Specifically, what is the numerator and denominator in the ratio?

Thanks!


The processor usage percent is calculated with "the amount of time that the processor is not on idle". I mean, this calc is made from a counter that register the usage of the "idle" running process. While another preocesses "rob" the processor power from the idle process, the idle processor consumer register is decreased by a factor; as the time line is fixed and constant, the (1-"%time in the idle taks") is the amount of processor load used for all processes running on a processor:

enter image description here

Defining CPU utilization

For our purposes, I define CPU utilization, U, as the amount of time not in the idle task, as shown in Equation 1.

The idle task is the task with the absolute lowest priority in a multitasking system. This task is also sometimes called the background task or background loop, shown in Listing 1. This logic traditionally has a while(1) type of loop. In other words, an infinite loop spins the CPU waiting for an indication that critical work needs to be done.

Listing 1: Simple example of a background loop

int main( void )
{
   SetupInterrupts();
   InitializeModules();
   EnableInterrupts();

   while(1)      /* endless loop - spin in the background */
   {
      CheckCRC();
      MonitorStack();
      ... do other non-time critical logic here.
   }
}

This depiction is actually an oversimplification, as some "real" work is often done in the background task. However, the logic coded for execution during the idle task must have no hard real-time requirements because there's no guarantee when this logic will complete. In fact, one technique you can use in an overloaded system is to move some of the logic with less strict timing requirements out of the hard real-time tasks and into the idle task.