Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate number of processor cores in PHP script (linux)?

I'm trying to use pthreads for multithreading. I'm creating pool with constructor. First parameter is number of Workers.

$pool = new Pool(8, 'WebWorker');

I want to detect count of processor cores automatically. Something like this:

$pool = new Pool(get_processor_cores_number(), 'WebWorker');

How is it possible with PHP?

like image 215
Nick Avatar asked May 01 '16 18:05

Nick


1 Answers

If the server is a Linux machine you can do it with the following snippet:

$ncpu = 1;

if(is_file('/proc/cpuinfo')) {
    $cpuinfo = file_get_contents('/proc/cpuinfo');
    preg_match_all('/^processor/m', $cpuinfo, $matches);
    $ncpu = count($matches[0]);
}
like image 111
teknoraver Avatar answered Sep 18 '22 12:09

teknoraver