Created
October 28, 2011 03:53
-
-
Save ezzatron/1321581 to your computer and use it in GitHub Desktop.
Function to detect number of CPUs in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Copyright © 2011 Erin Millard | |
*/ | |
/** | |
* Returns the number of available CPU cores | |
* | |
* Should work for Linux, Windows, Mac & BSD | |
* | |
* @return integer | |
*/ | |
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; |
For something under Apache license there is always Zeta Components SystemInfo: https://github.com/zetacomponents/SystemInformation/blob/master/src/info.php#L65-L73
@adduc just made a copyLEFT version, you can fork it and add whatever license you'd like, https://gist.github.com/divinity76/01ef9ca99c111565a72d3a8a6e42f7fb
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@duzun then at least reduce nesting a bit: