PHP教學-抓取主機 CPU 核心數
利用 php 可以偵測 windows 系統中 cpu 的核心數,範例程式如下:
<?php
function num_cpus()
{
$numCpus = 1;
if (is_file('/proc/cpuinfo'))
{
$cpuinfo = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpuinfo, $matches);
$numCpus = count($matches[0]);
}
else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3)))
{
$process = @popen('wmic cpu get NumberOfCores', 'rb');
if (false !== $process)
{
fgets($process);
$numCpus = intval(fgets($process));
pclose($process);
}
}
else
{
$process = @popen('sysctl -a', 'rb');
if (false !== $process)
{
$output = stream_get_contents($process);
preg_match('/hw.ncpu: (\d+)/', $output, $matches);
if ($matches)
{
$numCpus = intval($matches[1][0]);
}
pclose($process);
}
}
return $numCpus;
}
echo num_cpus().PHP_EOL;
例如本機 cpu 為雙核心 i7 2個超執行緒,那麼僅會偵測實體 cpu 核心數量。
<?php
function num_cpus()
{
$numCpus = 1;
if (is_file('/proc/cpuinfo'))
{
$cpuinfo = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpuinfo, $matches);
$numCpus = count($matches[0]);
}
else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3)))
{
$process = @popen('wmic cpu get NumberOfCores', 'rb');
if (false !== $process)
{
fgets($process);
$numCpus = intval(fgets($process));
pclose($process);
}
}
else
{
$process = @popen('sysctl -a', 'rb');
if (false !== $process)
{
$output = stream_get_contents($process);
preg_match('/hw.ncpu: (\d+)/', $output, $matches);
if ($matches)
{
$numCpus = intval($matches[1][0]);
}
pclose($process);
}
}
return $numCpus;
}
echo num_cpus().PHP_EOL;
例如本機 cpu 為雙核心 i7 2個超執行緒,那麼僅會偵測實體 cpu 核心數量。
留言
張貼留言