note 129847 added to function.sys-getloadavg

From: Date: Tue, 12 Nov 2024 02:45:45 +0000
Subject: note 129847 added to function.sys-getloadavg
Groups: php.notes 
Request: Send a blank email to php-notes+get-221644@lists.php.net to get a copy of this message
// 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>'; ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 58.96.37.13) ---- Manual Page -- https://php.net/manual/en/function.sys-getloadavg.php Edit -- https://main.php.net/note/edit/129847 Del: integrated -- https://main.php.net/note/delete/129847/integrated Del: useless -- https://main.php.net/note/delete/129847/useless Del: bad code -- https://main.php.net/note/delete/129847/bad+code Del: spam -- https://main.php.net/note/delete/129847/spam Del: non-english -- https://main.php.net/note/delete/129847/non-english Del: in docs -- https://main.php.net/note/delete/129847/in+docs Del: other reasons-- https://main.php.net/note/delete/129847 Reject -- https://main.php.net/note/reject/129847 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221644) next »