Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

debian - Get cpu percent usage in php

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 found on internet but nothing was useful. With load average I can't display 0-100% graphic bar and functions I found for percentage output give me bad values or only value for first core. It would be nice to get number of percentage usage for every core. Is there solution for this?

EDIT:

I make temporary solution, it works good but it is not best way.

cron job every one minute run php script which exec command for grep cpu info from "top" and save it to file, on end script wait 3 seconds and loop 20-times (way to get update every 3 seconds) php script:

<?php
for($i=0; $i<=20; $i++) {
    //cpu load
    exec("top -b -n 1 | grep 'Cpu(s):' > /some/file.cpu");
    //ram usage
    exec("top -b -n 1 | grep 'Mem:' > /some/file.ram");
    //wait 3sec
    sleep(3);
}
?>

and now from this files I can parse informations.

New question is how to make daemon script to run this commands every 3 seconds. I think solution with php script and cron is only temporary solution and is not best way. daemon will be much better.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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']


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...