Fishtrap

php and other stuff I know

Extension to find the number of processors with PHP

| 0 comments

While working on a script to generate fractals in PHP I wanted to try and run the intensive calculations in parallel. The script I came up with has a fair amount of overhead in spawning and managing a thread since they actually each write a file to disk. So the logical optimal number of threads was the number of available processor cores. I was surprised to find there didn’t seem to be an easy way to get the number of processors in PHP. I found a short C script that seemed to do the trick. So I knocked together a quick PHP extension called num_procs. It seems to work on linux and OSX which is good enough for me.

The code is on github

To install just do

git clone git://github.com/natmchugh/PHP-Num-Processors.git
cd PHP-Num-Processors
phpize
./configure
make
sudo make install

Then add …

extension=num_procs.so

.. to your php.ini

It exports two functions

$available = num_processors_available();
var_dump($available); // int(2)
$configured = num_processors_configured();
var_dump($configured); //int(2)

The effect of parallelising the calculations was pretty dramatic by the way speed up execution by 50% at least. I intend to write a post on that sometime.

Leave a Reply

Required fields are marked *.