The CPU does not perform usage calculations on its own. It may have hardware features that facilitate this task, but it is mainly the task of the operating system. Thus, it is obvious that implementation details will be different (especially in the case of multi-core systems).
The general idea is to see how long the processor queue takes. The operating system can periodically look at the scheduler to determine the number of things that it needs to perform.
This is a Linux function (torn out from Wikipedia) that performs the specified calculation :
#define FSHIFT 11 /* nr of bits of precision */ #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */ #define LOAD_FREQ (5*HZ) /* 5 sec intervals */ #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */ #define EXP_5 2014 /* 1/exp(5sec/5min) */ #define EXP_15 2037 /* 1/exp(5sec/15min) */ #define CALC_LOAD(load,exp,n) \ load *= exp; \ load += n*(FIXED_1-exp); \ load >>= FSHIFT; unsigned long avenrun[3]; static inline void calc_load(unsigned long ticks) { unsigned long active_tasks; /* fixed-point */ static int count = LOAD_FREQ; count -= ticks; if (count < 0) { count += LOAD_FREQ; active_tasks = count_active_tasks(); CALC_LOAD(avenrun[0], EXP_1, active_tasks); CALC_LOAD(avenrun[1], EXP_5, active_tasks); CALC_LOAD(avenrun[2], EXP_15, active_tasks); } }
As for the second part of your question, most modern operating systems are multitasking . This means that the OS is not going to allow programs to take up all the processing time and not have for themselves (if you do not) . In other words, even if the application is stuck, the OS can still steal some time for its work.
In silico Sep 20 '10 at 1:22 2010-09-20 01:22
source share