Get cpu percent usage in php

前端 未结 5 1388
生来不讨喜
生来不讨喜 2020-12-16 17:01

I want to show percent CPU usage in PHP. Is not important if get values by cron in shell > output to file > parse in PHP or directly get value in php. I try many solutions f

5条回答
  •  长情又很酷
    2020-12-16 17:43

    after searching on forums and trying many methods, best accurate is this:

    $stat1 = file('/proc/stat'); 
    sleep(1); 
    $stat2 = file('/proc/stat'); 
    $info1 = explode(" ", preg_replace("!cpu +!", "", $stat1[0])); 
    $info2 = explode(" ", preg_replace("!cpu +!", "", $stat2[0])); 
    $dif = array(); 
    $dif['user'] = $info2[0] - $info1[0]; 
    $dif['nice'] = $info2[1] - $info1[1]; 
    $dif['sys'] = $info2[2] - $info1[2]; 
    $dif['idle'] = $info2[3] - $info1[3]; 
    $total = array_sum($dif); 
    $cpu = array(); 
    foreach($dif as $x=>$y) $cpu[$x] = round($y / $total * 100, 1);
    

    now stats are in $cpu['user'], $cpu['nice'], $cpu['sys'], $cpu['idle']

提交回复
热议问题