View Single Post
Old 04-26-2009, 06:28 PM   #1 (permalink)
Sam Granger
The Acquainted
 
Join Date: Sep 2007
Posts: 126
Thanks: 4
Sam Granger is on a distinguished road
Default CPU load function - division by zero error :(

The following function seems to give me a Division by Zero error - not all the time but quite a lot of the time.

PHP Code:
class Linux_Server extends ServerLoad {
    function 
loadAverage($bar false) {
        
$results = array();
        if (
$fd = @fopen('/proc/loadavg''r')) {
            
$results['avg'] = preg_split("/\s/"fgets($fd4096),4);
            unset(
$results['avg'][3]);    // don't need the extra values, only first three
            
fclose($fd);
        } else {
            
$results['avg'] = array('N.A.''N.A.''N.A.');
        } 
        if (
$bar) {
            if (
$fd = @fopen('/proc/stat''r')) {
                
fscanf($fd"%*s %Ld %Ld %Ld %Ld"$ab$ac$ad$ae);
                
// Find out the CPU load
                // user + sys = load 
                // total = total
                
$load $ab $ac $ad;    // cpu.user + cpu.sys
                
$total $ab $ac $ad $ae;    // cpu.total
                
fclose($fd);

                
// we need a second value, wait 1 second befor getting (< 1 second no good value will occure)
                
sleep(1);
                
$fd fopen('/proc/stat''r');
                
fscanf($fd"%*s %Ld %Ld %Ld %Ld"$ab$ac$ad$ae);
                
$load2 $ab $ac $ad;
                
$total2 $ab $ac $ad $ae;
                
$results['cpupercent'] = (100*($load2 $load)) / ($total2 $total);
                
fclose($fd);
            }
        }
        return 
$results;
    }

PHP Code:
$results['cpupercent'] = (100*($load2 $load)) / ($total2 $total); 
- the line that gives the error.

What am I doing wrong?
Sam Granger is offline  
Reply With Quote