Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class CPUInfo {
- public static function getCpuUsage($samples = 5) {
- $cmd = 'grep cpu /proc/stat';
- exec($cmd, $output1);
- $cpus1 = self::parseCpuStats($output1);
- $data = [];
- for ($i = 0; $i < $samples; $i++) {
- usleep(50000);
- $output2 = [];
- exec($cmd, $output2);
- $cpus2 = self::parseCpuStats($output2);
- foreach ($cpus1 as $cpu => $value) {
- if (!isset($data[$cpu])) $data[$cpu] = 0;
- $total = $cpus2[$cpu]['idle'] - $value['idle'] + $cpus2[$cpu]['work'] - $value['work'];
- $data[$cpu] += ($cpus2[$cpu]['work'] - $value['work']) / $total;
- }
- $cpus1 = $cpus2;
- }
- foreach ($data as $cpu => $value) {
- $data[$cpu] = $data[$cpu] / $samples * 100;
- }
- var_dump($data);
- }
- public static function parseCpuStats($stat_cpuinfo) {
- $cpus = [];
- $first = true;
- foreach ($stat_cpuinfo as $line) {
- $line = preg_replace('!\s+!', ' ', $line);
- $parts = explode(' ', $line);
- $cpu = $parts[0];
- unset($parts[0]);
- $line = implode(' ', $parts);
- sscanf($line,
- "%D %D %D %D %D %D %D %D %D %D",
- $user, $nice, $system, $idle, $iowait, $irq, $softirq, $steal, $guest, $guestnice
- );
- if ($first) {
- $cpus['ALL'] = [
- 'work' => $user + $nice + $system + $irq + $softirq + $steal,
- 'idle' => $idle + $iowait
- ];
- }
- else {
- $cpus[$cpu] = [
- 'work' => $user + $nice + $system + $irq + $softirq + $steal,
- 'idle' => $idle + $iowait
- ];
- }
- $first = false;
- }
- return $cpus;
- }
- public static function getRamUsage() {
- $free = trim(shell_exec('free'));
- // $free = (string)trim($free);
- $free_arr = explode("\n", $free);
- $ret = [
- 'hard' => [
- 'total' => 0,
- 'used' => 0,
- 'percent' => 0,
- ],
- 'swap' => [
- 'total' => 0,
- 'used' => 0,
- 'percent' => 0,
- ]
- ];
- foreach ($free_arr as $line) {
- if (!preg_match('/(Mem|Swap).*/', $line)) continue;
- $mem_line = explode(" ", $line);
- $mem_clean = array_merge(array_filter($mem_line));
- $memory_usage = $mem_clean[2]/$mem_clean[1]*100;
- if (preg_match('/Mem/', $line)) {
- $ret['hard']['percent'] = $memory_usage;
- $ret['hard']['total'] = (int)$mem_clean[2];
- $ret['hard']['used'] = (int)$mem_clean[1];
- }
- if (preg_match('/Swap/', $line)) {
- $ret['swap']['percent'] = $memory_usage;
- $ret['swap']['total'] = (int)$mem_clean[2];
- $ret['swap']['used'] = (int)$mem_clean[1];
- }
- }
- return $ret;
- }
- }
Add Comment
Please, Sign In to add comment