TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   CPU load function - division by zero error :( (http://www.talkphp.com/general/4190-cpu-load-function-division-zero-error.html)

Sam Granger 04-26-2009 06:28 PM

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 04-26-2009 10:01 PM

Doh! total and total2 sre the same value in many cases ofcourse! Silly me. Solved :)


All times are GMT. The time now is 06:50 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0