php-获取本机电脑内存使用情况

2021-04-08 13:32 阅读:2177

如果您需要整个系统的整体内存使用量,则以下功能可能会有所帮助。 如果通过返回具有系统可用内存和整体内存的数组来检索内存使用率(以百分比(无百分号))或以字节为单位。 在Windows(7)和Linux(在Raspberry Pi 2上)上进行了测试

Memory.php

<?php

class Memory
{
    // 返回已用内存:以百分比(无百分号)或可用内存和总字节数为单位
    public static function getServerMemoryUsage($getPercentage=true)
    {
        $memoryTotal = null;
        $memoryFree = null;

        if (stristr(PHP_OS, "win")) {
            // 获取总物理内存(以字节为单位)
            $cmd = "wmic ComputerSystem get TotalPhysicalMemory";
            @exec($cmd, $outputTotalPhysicalMemory);

            // 获取可用的物理内存(以千字节为单位!)
            $cmd = "wmic OS get FreePhysicalMemory";
            @exec($cmd, $outputFreePhysicalMemory);

            if ($outputTotalPhysicalMemory && $outputFreePhysicalMemory) {
                // 查找总大小
                foreach ($outputTotalPhysicalMemory as $line) {
                    if ($line && preg_match("/^[0-9]+\$/", $line)) {
                        $memoryTotal = $line;
                        break;
                    }
                }

                // 查找剩余大小
                foreach ($outputFreePhysicalMemory as $line) {
                    if ($line && preg_match("/^[0-9]+\$/", $line)) {
                        $memoryFree = $line;
                        $memoryFree *= 1024;  // 从千字节转换为字节
                        break;
                    }
                }
            }
        }
        else
        {
            if (is_readable("/proc/meminfo"))
            {
                $stats = @file_get_contents("/proc/meminfo");

                if ($stats !== false) {
                    // 分行
                    $stats = str_replace(array("\r\n", "\n\r", "\r"), "\n", $stats);
                    $stats = explode("\n", $stats);

                    // Separate values and find correct lines for total and free mem
                    foreach ($stats as $statLine) {
                        $statLineData = explode(":", trim($statLine));

                        // 总内存
                        if (count($statLineData) == 2 && trim($statLineData[0]) == "MemTotal") {
                            $memoryTotal = trim($statLineData[1]);
                            $memoryTotal = explode(" ", $memoryTotal);
                            $memoryTotal = $memoryTotal[0];
                            $memoryTotal *= 1024;  // 从千字节转换为字节
                        }

                        // 可用内存
                        if (count($statLineData) == 2 && trim($statLineData[0]) == "MemFree") {
                            $memoryFree = trim($statLineData[1]);
                            $memoryFree = explode(" ", $memoryFree);
                            $memoryFree = $memoryFree[0];
                            $memoryFree *= 1024;  // 从千字节转换为字节
                        }
                    }
                }
            }
        }

        if (is_null($memoryTotal) || is_null($memoryFree)) {
            return null;
        } else {
            if ($getPercentage) {
                return (100 - ($memoryFree * 100 / $memoryTotal));
            } else {
                return array(
                    "total" => $memoryTotal,
                    "free" => $memoryFree,
                );
            }
        }
    }

    /**
     * 将字节单位转为简写(提高可读性)
     * @param integer $bytes 内存字节
     * @param bool $binaryPrefix 二进制前缀
     * @return string
     */
    public static function getNiceFileSize($bytes, $binaryPrefix=true) {
        if ($binaryPrefix) {
            $unit=array('B','KiB','MiB','GiB','TiB','PiB');
            if ($bytes==0) return '0 ' . $unit[0];
            return @round($bytes/pow(1024,($i=floor(log($bytes,1024)))),2) .' '. (isset($unit[$i]) ? $unit[$i] : 'B');
        } else {
            $unit=array('B','KB','MB','GB','TB','PB');
            if ($bytes==0) return '0 ' . $unit[0];
            return @round($bytes/pow(1000,($i=floor(log($bytes,1000)))),2) .' '. (isset($unit[$i]) ? $unit[$i] : 'B');
        }
    }
}

使用实例:

// 内存使用: 10.33 GiB / 15.52 GiB (66.5591246192%)
$memUsage = Memory::getServerMemoryUsage(false);
echo sprintf("内存使用: %s / %s (%s%%)",
    Memory::getNiceFileSize($memUsage["total"] - $memUsage["free"]),
    Memory::getNiceFileSize($memUsage["total"]),
    Memory::getServerMemoryUsage(true)
);

{{commentTotal}} 条评论

{{item.nickname}}
{{item.create_date}}
{{item.content}}
- 上拉或点击加载更多 -
- 加载中 -
- 没有更多了 -
- 本文链接 -