/
CpuCoreCountProvider.php
62 lines (60 loc) · 1.76 KB
/
CpuCoreCountProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare (strict_types=1);
namespace RectorPrefix202212\Symplify\EasyParallel;
use RectorPrefix202212\Nette\Utils\Strings;
/**
* From https://github.com/phpstan/phpstan-src/commit/9124c66dcc55a222e21b1717ba5f60771f7dda92
*/
final class CpuCoreCountProvider
{
/**
* @see https://regex101.com/r/XMeAl4/1
* @var string
*/
private const PROCESSOR_REGEX = '#^processor#m';
/**
* @var int
*/
private const DEFAULT_CORE_COUNT = 2;
public function provide() : int
{
// from brianium/paratest
$cpuInfoCount = $this->resolveFromProcCpuinfo();
if ($cpuInfoCount !== null) {
return $cpuInfoCount;
}
$coreCount = self::DEFAULT_CORE_COUNT;
if (\DIRECTORY_SEPARATOR === '\\') {
// Windows
$process = @\popen('wmic cpu get NumberOfCores', 'rb');
if ($process !== \false) {
\fgets($process);
$coreCount = (int) \fgets($process);
\pclose($process);
}
return $coreCount;
}
$process = @\popen('sysctl -n hw.ncpu', 'rb');
if ($process !== \false) {
$coreCount = (int) \fgets($process);
\pclose($process);
}
return $coreCount;
}
private function resolveFromProcCpuinfo() : ?int
{
if (!\is_file('/proc/cpuinfo')) {
return null;
}
// Linux (and potentially Windows with linux sub systems)
$cpuinfo = \file_get_contents('/proc/cpuinfo');
if ($cpuinfo === \false) {
return null;
}
$matches = Strings::matchAll($cpuinfo, self::PROCESSOR_REGEX);
if ($matches === []) {
return 0;
}
return \count($matches);
}
}