Featured

Some article you should watch….

Google Reader

some article I share in google reader. they are very important to me.

Headline

Most important article~

Normal

原創

通常 原創都是短短的 因為站長很忙.

Home » Normal

CPU-LOADing Detect function

Submitted by tung on June 29, 2010 – 1:42 pmNo Comment
CPU-LOADing Detect function

Sometime you need to detect cup loading on server.
This function was support window and linux cpu loading detect.

function GetCpuLoad($Check=false, $NoComment=false)
{
    if (!PHP_OS) return ($Check)?-1:0;
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        global $Settings;
        if (!$Settings || !trim(ValidVar($Settings['All']->CPU_AVG_PATH))) return ($Check)?-1:0;
        $Data=@exec("\"".$Settings['All']->CPU_AVG_PATH."\"");
    }
    else $Data = @exec("uptime");
    if (!$Data) return ($Check)?-1:0;
    if (!$NoComment&&!$Check) echo $Data."\n";
    $Arr=array();
    @preg_match_all("/\d+[,\.]\d+/",$Data,$Arr);
    if (!isset($Arr[0][0])) return ($Check)?-1:0;
    $Data=$Arr[0][0];
    $Data=str_replace(",",".",$Data);
    return trim($Data);
}

How to work:

echo "CPU:",GetCpuLoad(true),"\n";
echo "CPU:",GetCpuLoad(true,true),"\n";
echo "CPU:",GetCpuLoad(),"\n";

Result:

CPU:0.08
CPU:0.08
CPU: 16:02:42 up 13 days,  6:35,  2 users,  load average: 0.08, 0.15, 0.11

Comments are closed.