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 8, 2022
1 parent c9d76cb commit 7f5522e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 45 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
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.3.0",
"hoa/compiler": "3.17.08.08",
"hoa/exception": "^1.0",
"hoa/regex": "1.17.01.13",
Expand Down
51 changes: 6 additions & 45 deletions src/Process/CpuCoreCounter.php
Original file line number Diff line number Diff line change
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,11 @@ public function getNumberOfCpuCores(): int
return $this->count;
}

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

}

0 comments on commit 7f5522e

Please sign in to comment.