Skip to content

Commit

Permalink
Improve CPU core count detection: integrate FidryCpuCoreCounter (#1767)
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`
- add more ways to detect the CPU core counts
- better handling of failures
  • Loading branch information
theofidry committed Dec 11, 2022
1 parent eb7b821 commit b784620
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 51 deletions.
1 change: 1 addition & 0 deletions composer.json
Expand Up @@ -50,6 +50,7 @@
"composer-runtime-api": "^2.0",
"colinodell/json5": "^2.2",
"composer/xdebug-handler": "^2.0 || ^3.0",
"fidry/cpu-core-counter": "^0.4.0",
"infection/abstract-testframework-adapter": "^0.5.0",
"infection/extension-installer": "^0.1.0",
"infection/include-interceptor": "^0.2.5",
Expand Down
65 changes: 63 additions & 2 deletions composer.lock

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

54 changes: 5 additions & 49 deletions src/Resource/Processor/CpuCoresCountProvider.php
Expand Up @@ -36,17 +36,8 @@
namespace Infection\Resource\Processor;

use function defined;
use function extension_loaded;
use const FILTER_VALIDATE_INT;
use function filter_var;
use function function_exists;
use function is_int;
use function is_readable;
use Safe\Exceptions\ExecException;
use function Safe\file_get_contents;
use function Safe\shell_exec;
use function substr_count;
use function trim;
use Fidry\CpuCoreCounter\CpuCoreCounter;
use Fidry\CpuCoreCounter\NumberOfCpuCoreNotFound;

/**
* @internal
Expand All @@ -62,45 +53,10 @@ public static function provide(): int
return 1;
}

if (!extension_loaded('pcntl') || !function_exists('shell_exec')) {
return 1;
}

try {
// for Linux
$hasNproc = trim(@shell_exec('command -v nproc'));

if ($hasNproc !== '') {
$nproc = trim(shell_exec('nproc'));
$cpuCount = filter_var($nproc, FILTER_VALIDATE_INT);

if (is_int($cpuCount)) {
return $cpuCount;
}
}
} catch (ExecException) {
}

try {
// for MacOS
$ncpu = trim(shell_exec('sysctl -n hw.ncpu'));
$cpuCount = filter_var($ncpu, FILTER_VALIDATE_INT);

if (is_int($cpuCount)) {
return $cpuCount;
}
} catch (ExecException) {
}

if (is_readable('/proc/cpuinfo')) {
$cpuInfo = file_get_contents('/proc/cpuinfo');
$cpuCount = substr_count($cpuInfo, 'processor');

if ($cpuCount > 0) {
return $cpuCount;
}
return (new CpuCoreCounter())->getCount();
} catch (NumberOfCpuCoreNotFound $exception) {
return 1;
}

return 1;
}
}

0 comments on commit b784620

Please sign in to comment.