使用php代码获取Linux上的cpu信息

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

<?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";
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注