Created
June 13, 2018 12:40
-
-
Save divinity76/01ef9ca99c111565a72d3a8a6e42f7fb to your computer and use it in GitHub Desktop.
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 | |
/** | |
* returns number of cpu cores | |
* Copyleft 2018, license: WTFPL | |
* @throws \RuntimeException | |
* @throws \LogicException | |
* @return int | |
*/ | |
function num_cpu(): int { | |
if (defined ( 'PHP_WINDOWS_VERSION_MAJOR' )) { | |
$str = trim ( shell_exec ( 'wmic cpu get NumberOfCores 2>&1' ) ); | |
if (! preg_match ( '/(\d+)/', $str, $matches )) { | |
throw new \RuntimeException ( 'wmic failed to get number of cpu cores on windows!' ); | |
} | |
return (( int ) $matches [1]); | |
} | |
$ret = @shell_exec ( 'nproc' ); | |
if (is_string ( $ret )) { | |
$ret = trim ( $ret ); | |
if (false !== ($tmp = filter_var ( $ret, FILTER_VALIDATE_INT ))) { | |
return $tmp; | |
} | |
} | |
if (is_readable ( '/proc/cpuinfo' )) { | |
$cpuinfo = file_get_contents ( '/proc/cpuinfo' ); | |
$count = substr_count ( $cpuinfo, 'processor' ); | |
if ($count > 0) { | |
return $count; | |
} | |
} | |
throw new \LogicException( 'failed to detect number of CPUs!' ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment