[PHP]How to get the number of CPU cores in Fedora, Ubuntu, and FreeBSD

I am working on a PHP application which needs to be deploy to multiple places. One of the variables is the number of CPU core. Since each server has different number of CPU cores, I need to specify the number of CPU core in my application for each server. I think there should be a smarter way to do it.

PHP is a scripting language, it has limit support on accessing the hardware level information. In short, there is no library or function to do it. Fortunately, we can do it via shell command. In the other words, the following methods are not limited to PHP, it will work in any languages, as long as your language supports running the UNIX command and catch the return.

Getting the number of CPU Cores – Linux

(Tested on Fedora, Ubuntu Linux, should work on other Linuxs because they all use the same Linux kernel.)

cat /proc/cpuinfo | grep processor | wc -l

This will return something like this:

8

Getting the number of CPU Cores – FreeBSD

sysctl -a | grep 'hw.ncpu' | cut -d ':' -f2

which will return something like this (notice the extra space before the number):

8

Now, let’s put everything together. Run the command inside your application (Here I am using PHP for example):

//Linux
$cmd = "cat /proc/cpuinfo | grep processor | wc -l";

//FreeBSD
$cmd = "sysctl -a | grep 'hw.ncpu' | cut -d ':' -f2";

$cpuCoreNo = intval(trim(shell_exec($cmd)));

Of course, you can make the application to detect the system automatically:

$cmd = "uname";
$OS = strtolower(trim(shell_exec($cmd)));

switch($OS){
   case('linux'):
      $cmd = "cat /proc/cpuinfo | grep processor | wc -l";
      break;

   case('freebsd'):
      $cmd = "sysctl -a | grep 'hw.ncpu' | cut -d ':' -f2";
      break;

   default:
      unset($cmd);
}

if ($cmd != ''){
   $cpuCoreNo = intval(trim(shell_exec($cmd)));
}

That’s it! Happy PHPing.

–Derrick

Our sponsors:

4 Replies to “[PHP]How to get the number of CPU cores in Fedora, Ubuntu, and FreeBSD”

  1. David Morgan

    Thanks for this! I was playing around with various ways of accomplishing the same thing, and came up with a quick and dirty one-liner using Python that works great under Linux. (Tested with Ubuntu 12.04 anyway)

    $core_count = exec(“printf ‘import multiprocessing \nprint multiprocessing.cpu_count()’ | python”);

    Reply
  2. Dmitri

    Do you actually see core number with the string below?

    $cmd = “cat /proc/cpuinfo | grep processor | wc -l”;

    I tried it on two servers, one is single Xeon E5-2697 v2, another – dual Xeon E5-2690, but getting “1” for the first server and just “2” for the second.

    I believe that /proc/stat should work better, but currently I’m still trying to write a proper code for that.

    Reply

Leave a Reply to David Morgan Cancel reply

Your email address will not be published. Required fields are marked *