Voting

: eight plus zero?
(Example: nine)

The Note You're Voting On

seb dot gibbs at ymail dot com
7 months ago
// To get correct number of CPU cores
// as to calculate correct usage

function getCpuCores() {
// Linux
if (stristr(PHP_OS, 'linux')) {
// First, try /proc/cpuinfo
if (file_exists('/proc/cpuinfo')) {
preg_match_all('/^processor/m', file_get_contents('/proc/cpuinfo'), $matches);
if ($matches[0]) return count($matches[0]);
}
// Fallback: Use nproc command
return (int)shell_exec('nproc');
}

// macOS
if (stristr(PHP_OS, 'darwin')) {
return (int)shell_exec('sysctl -n hw.physicalcpu');
}

// Windows
if (stristr(PHP_OS, 'win')) {
// Try wmic command first
$cpuCount = shell_exec('wmic cpu get NumberOfLogicalProcessors');
if ($cpuCount) {
preg_match('/\d+/', $cpuCount, $matches);
if (isset($matches[0])) return (int)$matches[0];
}
// Fallback: Use environment variable
return (int)getenv('NUMBER_OF_PROCESSORS');
}

// If failed
return false;
}

// Example usage
// get CPU cores
$cores = getCpuCores();

if (is_Numeric($cores)) {
$corePerc = 100/$cores;
} else {
$corePerc = 100;
$cores = 'Unknown';
}
echo '<div><b>CPU:</b> '.$cores .' cores</div>';

// show correct CPU usage
echo '<blockquote>';
$cpu = sys_getloadavg();
echo(round($cpu[0]*$corePerc) .'% - last min<br>');
echo(round($cpu[1]*$corePerc) .'% - last 5 mins<br>');
echo(round($cpu[2]*$corePerc) .'% - last 15 mins<br>');
echo '</blockquote>';

<< Back to user notes page

To Top