function getMemoryInfo() {
// 读取 /proc/meminfo 文件内容
$meminfo = file('/proc/meminfo');
$freeMemory = 0;
$availableMemory = 0;
$totalMemory = 0;
foreach ($meminfo as $line) {
if (strpos($line, 'MemTotal:') === 0) {
// 获取总内存(MemTotal)
list(, $memTotalKb) = explode(':', trim($line));
$totalMemory = (int)$memTotalKb * 1024; // 转换为字节
} elseif (strpos($line, 'MemFree:') === 0) {
// 获取完全没有被使用的内存(MemFree)
list(, $memFreeKb) = explode(':', trim($line));
$freeMemory = (int)$memFreeKb * 1024; // 转换为字节
} elseif (strpos($line, 'Buffers:') === 0) {
// 获取被用作缓冲区的内存(Buffers)
list(, $buffersKb) = explode(':', trim($line));
$buffersMemory = (int)$buffersKb * 1024; // 转换为字节
} elseif (strpos($line, 'Cached:') === 0) {
// 获取被用作缓存的内存(Cached)
list(, $cachedKb) = explode(':', trim($line));
$cachedMemory = (int)$cachedKb * 1024; // 转换为字节
}
}
// 可用内存 = MemFree + Buffers + Cached
$availableMemory = $freeMemory + $buffersMemory + $cachedMemory;
// 计算内存使用率(百分比)
$usedMemory = $totalMemory - $availableMemory;
$memoryUsagePercent = ($usedMemory / $totalMemory) * 100;
// 获取内存信息
$memoryInfo = getMemoryInfo();
// 打印空闲内存、可用内存、总内存和内存使用率(以MB为单位和百分比表示)
echo "Free Memory: " . number_format($memoryInfo['free'] / (1024 * 1024), 2, '.', '') . " MB\n";
echo "Available Memory: " . number_format($memoryInfo['available'] / (1024 * 1024), 2, '.', '') . " MB\n";
echo "Total Memory: " . number_format($memoryInfo['total'] / (1024 * 1024), 2, '.', '') . " MB\n";
echo "Memory Usage: " . number_format($memoryInfo['usage_percent'], 2, '.', '') . " %\n";
foreach ($meminfo as $line)
strpos($line, 'MemTotal:') === 0
list(, $memTotalKb) = explode(':', trim($line));
trim($line);用于将$line首位的空白去掉去空白:MemTotal: 16384256 kB
分割成数组:["MemTotal", " 16384256 kB"]
return [
'free' => $freeMemory,
'available' => $availableMemory,
'total' => $totalMemory,
'usage_percent' => $memoryUsagePercent
];
返回函数,后续使用时,$memoryInfo = getMemoryInfo(); 调用$memoryInfo['free'],简洁明了number_format($memoryInfo['free'] / (1024 * 1024), 2, '.', '')
由于我取值时转为了字节,所以字节转到MB时,要计算,要让字节/1024*1024// 函数:获取所有网络接口的流量信息
function getAllNetworkTraffic() {
// 读取 /proc/net/dev 文件的内容
$stats = file('/proc/net/dev');
$totalTraffic = [
'totalReceiveBytes' => 0,
'totalTransmitBytes' => 0,
];
// 遍历每一行,除了前两行(标题和汇总行)
foreach ($stats as $lineNum => $line) {
// 跳过前两行
if ($lineNum < 2) {
continue;
}
// 使用正则表达式匹配网络接口的行并提取接收和发送的字节数
if (preg_match('/^\s*(\S+):\s+(\d+)\s+(\d+)/', $line, $matches)) {
$interface = $matches[1]; // 网络接口名称(可能包含冒号和数字,如 eth0:0)
$receiveBytes = intval($matches[2]);
$transmitBytes = intval($matches[3]);
// 累积接收和发送的字节数 //因为要获取前1秒的数据
$totalTraffic['totalReceiveBytes'] += $receiveBytes;
$totalTraffic['totalTransmitBytes'] += $transmitBytes;
}
}
// 返回总流量信息
return $totalTraffic;
}
// 获取初始的所有网络接口流量信息
$prevTotalTraffic = getAllNetworkTraffic();
// 等待一秒钟
sleep(1);
// 获取当前的所有网络接口流量信息
$currTotalTraffic = getAllNetworkTraffic();
// 检查是否成功获取了流量信息
if ($prevTotalTraffic && $currTotalTraffic) {
// 计算接收和发送的字节差异
$totalReceiveDiff = $currTotalTraffic['totalReceiveBytes'] - $prevTotalTraffic['totalReceiveBytes'];
$totalTransmitDiff = $currTotalTraffic['totalTransmitBytes'] - $prevTotalTraffic['totalTransmitBytes'];
// 将字节差异转换为 KB/s(千字节每秒),注意这里应该是 KBps 而不是 Kbps(因为 Kbps 通常指千比特每秒)
$totalReceiveSpeedKBps = $totalReceiveDiff / 1024;
$totalTransmitSpeedKBps = $totalTransmitDiff / 1024;
// 输出结果
//echo "所有接口综合下行流量(接收): " . number_format($totalReceiveSpeedKBps, 2, '.', '') . " KB/s\n";
// echo "所有接口综合上行流量(发送): " . number_format($totalTransmitSpeedKBps, 2, '.', '') . " KB/s\n";
} else {
// 如果无法获取流量信息,则输出错误信息
echo "无法获取所有网络接口的流量信息。\n";
}
(preg_match('/^\s*(\S+):\s+(\d+)\s+(\d+)/', $line, $matches)) {
$interface = $matches[1]; // 网络接口名称(可能包含冒号和数字,如 eth0:0)
$receiveBytes = intval($matches[2]);
$transmitBytes = intval($matches[3]);
$totalTraffic['totalReceiveBytes'] += $receiveBytes;
$totalTraffic['totalTransmitBytes'] += $transmitBytes;
将遍历的结果累计到变量// 获取初始的所有网络接口流量信息
$prevTotalTraffic = getAllNetworkTraffic();
// 等待一秒钟
sleep(1);
// 获取当前的所有网络接口流量信息
$currTotalTraffic = getAllNetworkTraffic();
当前的流量 - 1秒前的流量 = 1秒内的流量$directory = '/';
// 获取总磁盘空间和可用磁盘空间
$totalSpace = disk_total_space($directory);
$freeSpace = disk_free_space($directory);
$totalSpaceGB = $totalSpace / (1024 * 1024 * 1024); // 或者使用 1073741824,但这种方式更清晰
$freeSpaceGB = $freeSpace / (1024 * 1024 * 1024);
// 计算已用空间
$usedSpace = $totalSpace - $freeSpace;
$usedSpaceGB = $totalSpaceGB - $freeSpaceGB;
// 计算使用率(百分比)
$usagePercentage = ($usedSpace / $totalSpace) * 100;
function getCpuInfo() {
$stats = file('/proc/stat');
$cpuInfo = [];
foreach ($stats as $line) {
if (preg_match('/^cpu(\d*)\s+(.+)/', $line, $matches)) {
$cpu = $matches[1];
if ($cpu == '') {
$cpu = 'total';
}
$values = preg_split('/\s+/', $matches[2], -1, PREG_SPLIT_NO_EMPTY);
$cpuInfo[$cpu] = array_map('intval', $values);
}
}
return $cpuInfo;
}
function calculateCpuUsage($prev, $curr) {
$prevIdle = $prev['total'][3] + $prev['total'][4]; // idle + iowait (Linux 2.5.41+)
$currIdle = $curr['total'][3] + $curr['total'][4];
$prevNonIdle = array_sum($prev['total']) - $prevIdle;
$currNonIdle = array_sum($curr['total']) - $currIdle;
$prevTotal = array_sum($prev['total']);
$currTotal = array_sum($curr['total']);
$totalDiff = $currTotal - $prevTotal;
$idleDiff = $currIdle - $prevIdle;
$cpuUsage = 100 * (($totalDiff - $idleDiff) / $totalDiff);
return $cpuUsage;
}
// 获取初始 CPU 信息
$prevCpuInfo = getCpuInfo();
// 等待一秒(可以根据需要调整时间间隔)
sleep(1);
// 获取当前 CPU 信息
$currCpuInfo = getCpuInfo();
// 计算 CPU 使用率
$cpuUsage = calculateCpuUsage($prevCpuInfo, $currCpuInfo);
//echo "CPU Usage: " . number_format($cpuUsage, 2, '.', '') . "%\n";
作者: 小恶魔owo, 来源:面包板社区
链接: https://mbb.eet-china.com/blog/uid-me-4067534.html
版权声明:本文为博主原创,未经本人允许,禁止转载!
文章评论(0条评论)
登录后参与讨论