Number Of Available CPU Cores In PHP

It is simple enough to check and then load the number of available processing cores on the current machine into a PHP variable. You can do so with the code below, which uses shell commands to grab data from /proc/cpuinfo and then removes unneeded data with PHP.

<?php
 /*How to check how many processors are available on the current machine.
 by gordon@incero.com http://www.Incero.com. Feel free to use this code,
 but keep this header. June 30th, 2010.*/
 $numberOfProcessors=`cat /proc/cpuinfo | grep processor | tail -1`;
 $numberOfProcessors=preg_replace('/\s+/', '',$numberOfProcessors);
 $numberOfProcessors=str_replace(":","", $numberOfProcessors);
 $numberOfProcessors=str_replace("processor","", $numberOfProcessors);
 $numberOfProcessors++;
 echo "Number of processors on this machine is $numberOfProcessors!";
?>

We use this code to help our programs assign the most efficient parameters to others processes, such as FFMpeg video conversions, that we spawn from PHP across various machines.

Tested on CentOS 5.4, should work on most Linux distributions.

3 Responses to “Number Of Available CPU Cores In PHP”

  1. Sam says:

    Great script, I just used it in one of my projects. Knowing how many cores are available and combining that with “uptime” we can figure out how many more video conversion processes our script should launch at any current time.

  2. Adrien says:

    What about

    exec(“cat /proc/cpuinfo | grep processor | wc -l”,$processors);
    echo “Number of processors on this machine is $processors!”;

    I thought about it reading your code. I agree, it’s bash and not php.

    I use this to evaluate the load of the server (300% on a 8 cores is less than on a 4 cores)

  3. Gordon says:

    Yes, much better!

Leave a Reply