Skip to content

Instantly share code, notes, and snippets.

@divinity76
Created June 13, 2018 12:40
Show Gist options
  • Save divinity76/01ef9ca99c111565a72d3a8a6e42f7fb to your computer and use it in GitHub Desktop.
Save divinity76/01ef9ca99c111565a72d3a8a6e42f7fb to your computer and use it in GitHub Desktop.
<?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