Core\Os::cpuCount
Returns the number of CPU cores your program may use. The number is always 1 or more.
This is often smaller than the number of cores in the machine. A server can limit a program to some of its cores, and a container can too. A program in a container with 2 cores on a machine with 96 cores reads 2. The web server uses the same number to decide how many workers it starts.
Use it when your program decides how many pieces of work to run at the same time. The number is different on every machine, so do not write it into a file or a test.
The examples show how to read the number, how to give jobs out to the cores in turn, and how to choose the size of a pool of workers.
Return value
Returns uint. The number of cores. It is always 1 or more.
Errors
RuntimeErrorThe operating system did not say how many cores this program may use.
Examples
How many cores
<?nvs// Shows how to read the number of CPU cores your program may use.
uint $cores = Core\Os::cpuCount();
// The number is different on every machine, so this example only checks it.// `Core\Os::cpuCount` always returns 1 or more. This prints `yes`.echo $cores >= 1 ? 'yes' : 'no', "\n";yesSharing jobs between cores
<?nvs// Shows how to share jobs between the cores of a machine by giving them out in turn.
uint $jobs = 10;uint $cores = Core\Os::cpuCount();
// Job 0 goes to core 0, job 1 to core 1, and so on. After the last core, the// next job goes to core 0 again. `%` gives the rest of a division.uint $onFirstCore = 0;uint $job = 0;while ($job < $jobs) { if ($job % $cores == 0) { $onFirstCore = $onFirstCore + 1; } $job = $job + 1;}
// With one core, core 0 gets all 10 jobs. With more cores, it gets fewer, but// never 0. This prints `yes`.echo $onFirstCore >= 1 && $onFirstCore <= 10 ? 'yes' : 'no', "\n";yesSizing a worker pool
<?nvs// Shows how a program chooses how many workers to start for a batch of files.
array<string> $files = ['orders.csv', 'customers.csv', 'invoices.csv'];
// One worker per core is a good start. More workers than files do nothing,// so the pool is never larger than the number of files.uint $workers = Core\Os::cpuCount();if ($workers > Core\Arr::count($files)) { $workers = Core\Arr::count($files);}
// The pool has between 1 and 3 workers, on any machine. This prints `yes`.echo $workers >= 1 && $workers <= 3 ? 'yes' : 'no', "\n";yes