使用php代码获取Linux上的cpu频率和cpu名称
也许,是生活也是人生

这几天研究Linux系统方向的东西,使用到了Linux虚拟文件接口,将一些经常用到的封装成了方法,并且整理,如果正好需要的同学可以参考哦~

linux.png

<?php
declare (strict_types=1);

/**
 * 获取CPU名称
 * @return mixed
 */
function getSystemCpuName()
{
    $cpuFileInfo = implode("", file("/proc/cpuinfo"));
    preg_match_all("/model\s+name\s{0,}\:+\s{0,}([\w\s\)\(\@.-]+)([\r\n]+)/s", $cpuFileInfo, $model);
    return $model[1][0];
}


/**
 * 获取CPU频率
 * @return mixed
 */
function getSystemCpuMhz()
{
    $cpuFileInfo = implode("", file("/proc/cpuinfo"));
    preg_match_all("/cpu\s+MHz\s{0,}\:+\s{0,}([\d\.]+)[\r\n]+/", $cpuFileInfo, $mhz);
    return $mhz[1][0];
}

/**
 * 获取CPU二级缓存/单位KB
 * @return string
 */
function getSystemCpuCache()
{
    $cpuFileInfo = implode("", file("/proc/cpuinfo"));
    preg_match_all("/cache\s+size\s{0,}\:+\s{0,}([\d\.]+\s{0,}[A-Z]+[\r\n]+)/", $cpuFileInfo, $cache);
    return (int)trim(trim($cache[1][0]), PHP_EOL);
}

/**
 * 获取CPU的BogoMIPS
 * @return mixed
 */
function getSystemCpuBogoMIPS()
{
    $cpuFileInfo = implode("", file("/proc/cpuinfo"));
    preg_match_all("/bogomips\s{0,}\:+\s{0,}([\d\.]+)[\r\n]+/", $cpuFileInfo, $bogomips);
    return $bogomips[1][0];
}

/**
 * 获取CPU数量
 * @return int
 */
function getSystemCpuNum()
{
    $cpuFileInfo = implode("", file("/proc/cpuinfo"));
    preg_match_all("/model\s+name\s{0,}\:+\s{0,}([\w\s\)\(\@.-]+)([\r\n]+)/s", $cpuFileInfo, $model);
    return sizeof($model[1]);
}

echo "CPU名称:" . getSystemCpuName() . "\n";
echo "CPU频率:" . getSystemCpuMhz() . "\n";
echo "CPU二级缓存:" . getSystemCpuCache() . "\n";
echo "CPU计算速度:" . getSystemCpuBogoMIPS() . "\n";
echo "CPU数量:" . getSystemCpuNum() . "\n";

「也许,这就是人生」

发表评论