server/app/Utils/MemoryHelper.php

52 lines
1.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Utils;
class MemoryHelper
{
/**
* 获取系统内存使用情况
*
* @return array [
* 'total' => 总内存MB
* 'used' => 已用内存MB
* 'free' => 剩余内存MB
* 'usage' => 使用率(百分比)
* ]
*/
public static function getMemoryInfo(): array
{
$meminfo = self::readMeminfo();
$total = $meminfo['MemTotal'] ?? 0;
$free = ($meminfo['MemFree'] ?? 0)
+ ($meminfo['Buffers'] ?? 0)
+ ($meminfo['Cached'] ?? 0)
+ ($meminfo['SReclaimable'] ?? 0);
$used = $total - $free;
$usage = $total > 0 ? round($used / $total * 100, 2) : 0;
return [
'total' => round($total / 1024, 2), // 转 MB
'used' => round($used / 1024, 2),
'free' => round($free / 1024, 2),
'usage' => $usage,
];
}
/**
* 读取 /proc/meminfo 并返回数组
*/
private static function readMeminfo(): array
{
$data = [];
foreach (file('/proc/meminfo') as $line) {
if (preg_match('/^(\S+):\s+(\d+)/', $line, $matches)) {
$data[$matches[1]] = (int) $matches[2]; // 单位 kB
}
}
return $data;
}
}