server/app/Utils/CpuHelper.php

68 lines
1.7 KiB
PHP

<?php
namespace App\Utils;
class CpuHelper
{
/**
* 获取 CPU 核心数
*/
public static function getCpuCores(): int
{
return (int) shell_exec('nproc');
}
/**
* 获取 CPU 使用情况(用户、系统、空闲百分比)
*/
public static function getCpuUsage(int $interval = 1): array
{
$stat1 = self::readStat();
sleep($interval);
$stat2 = self::readStat();
$diff = [];
foreach ($stat1 as $key => $value) {
$diff[$key] = $stat2[$key] - $value;
}
$total = array_sum($diff);
if ($total == 0) {
return [
'user' => 0,
'system' => 0,
'idle' => 100,
];
}
return [
'user' => round(($diff['user'] + $diff['nice']) / $total * 100, 2),
'system' => round($diff['system'] / $total * 100, 2),
'idle' => round($diff['idle'] / $total * 100, 2),
];
}
/**
* 读取 /proc/stat 文件中的 CPU 信息
*/
private static function readStat(): array
{
$fh = fopen('/proc/stat', 'r');
$line = fgets($fh);
fclose($fh);
$parts = preg_split('/\s+/', trim($line));
// /proc/stat 第一行示例:
// cpu 3357 0 4313 1362393 0 0 0
return [
'user' => (int) $parts[1],
'nice' => (int) $parts[2],
'system' => (int) $parts[3],
'idle' => (int) $parts[4],
'iowait' => (int) ($parts[5] ?? 0),
'irq' => (int) ($parts[6] ?? 0),
'softirq'=> (int) ($parts[7] ?? 0),
];
}
}