Skip to content

Commit

Permalink
Improve the CPU core count detection
Browse files Browse the repository at this point in the history
See theofidry/cpu-core-counter#11 for the motivations.

The code should be sensibly the same, the notable differences are:

- fixed the deprecated usage of `hw.ncpu`
- /proc/cpuinfo is check _last_
- nproc is checked first (before was not checked at all, it's considered to be more accurate and less convoluted than cpuinfo though)
- not sure about the `return 2`, but this was not too clear [here](phpstan#514 (review)) neither. I could otherwise change the fallback value to return `1` if `proc_open` doesn't exist and 2 otherwise
- add more ways to find the CPU cores count
  • Loading branch information
theofidry committed Dec 10, 2022
1 parent 3c3b17f commit ea9605a
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 45 deletions.
1 change: 1 addition & 0 deletions composer.json
Expand Up @@ -10,6 +10,7 @@
"clue/ndjson-react": "^1.0",
"composer/ca-bundle": "^1.2",
"composer/xdebug-handler": "^3.0.3",
"fidry/cpu-core-counter": "^0.4.0",
"hoa/compiler": "3.17.08.08",
"hoa/exception": "^1.0",
"hoa/regex": "1.17.01.13",
Expand Down
63 changes: 62 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 7 additions & 44 deletions src/Process/CpuCoreCounter.php
Expand Up @@ -2,16 +2,8 @@

namespace PHPStan\Process;

use function count;
use function fgets;
use function file_get_contents;
use function function_exists;
use function is_file;
use function is_resource;
use function pclose;
use function popen;
use function preg_match_all;
use const DIRECTORY_SEPARATOR;
use Fidry\CpuCoreCounter\CpuCoreCounter as FidryCpuCoreCounter;
use Fidry\CpuCoreCounter\NumberOfCpuCoreNotFound;

class CpuCoreCounter
{
Expand All @@ -24,42 +16,13 @@ public function getNumberOfCpuCores(): int
return $this->count;
}

if (!function_exists('proc_open')) {
return $this->count = 1;
try {
$this->count = (new FidryCpuCoreCounter())->getCount();
} catch (NumberOfCpuCoreNotFound) {
$this->count = 1;
}

// from brianium/paratest
if (@is_file('/proc/cpuinfo')) {
// Linux (and potentially Windows with linux sub systems)
$cpuinfo = @file_get_contents('/proc/cpuinfo');
if ($cpuinfo !== false) {
preg_match_all('/^processor/m', $cpuinfo, $matches);
return $this->count = count($matches[0]);
}
}

if (DIRECTORY_SEPARATOR === '\\') {
// Windows
$process = @popen('wmic cpu get NumberOfLogicalProcessors', 'rb');
if (is_resource($process)) {
fgets($process);
$cores = (int) fgets($process);
pclose($process);

return $this->count = $cores;
}
}

$process = @popen('sysctl -n hw.ncpu', 'rb');
if (is_resource($process)) {
// *nix (Linux, BSD and Mac)
$cores = (int) fgets($process);
pclose($process);

return $this->count = $cores;
}

return $this->count = 2;
return $this->count;
}

}

0 comments on commit ea9605a

Please sign in to comment.