How to Get Number of CPU Cores using PHP Function (Platform Independent)


We can use the following PHP Function to return the number of CPU Cores in the current System. At Linux Servers, this is done via looking into processor information at device file /proc/cpuinfo. And on windows, this is obtained via the Windows Administration Command `wmic cpu get NumberOfCores`.

And for the rest – Unix/MAC this is done via `sysctl -a`.

With this function, we can throttle API based on the load average: Using sys_getloadavg and num_cpus in PHP to Throttle API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function getNumberOfCPUs() {
  $ans = 1;
  if (is_file('/proc/cpuinfo')) {
    $cpuinfo = file_get_contents('/proc/cpuinfo');
    preg_match_all('/^processor/m', $cpuinfo, $matches);
    $ans = count($matches[0]);
  } else if ('WIN' === strtoupper(substr(PHP_OS, 0, 3))) {
    $process = @popen('wmic cpu get NumberOfCores', 'rb');
    if (false !== $process) {
      fgets($process);
      $ans = intval(fgets($process));
      pclose($process);
    }
  } else {
    $ps = @popen('sysctl -a', 'rb');
    if (false !== $ps) {
      $output = stream_get_contents($ps);
      preg_match('/hw.ncpu: (\d+)/', $output, $matches);
      if ($matches) {
        $ans = intval($matches[1][0]);
      }
      pclose($ps);
    }
  }  
  return $ans;
}
function getNumberOfCPUs() {
  $ans = 1;
  if (is_file('/proc/cpuinfo')) {
    $cpuinfo = file_get_contents('/proc/cpuinfo');
    preg_match_all('/^processor/m', $cpuinfo, $matches);
    $ans = count($matches[0]);
  } else if ('WIN' === strtoupper(substr(PHP_OS, 0, 3))) {
    $process = @popen('wmic cpu get NumberOfCores', 'rb');
    if (false !== $process) {
      fgets($process);
      $ans = intval(fgets($process));
      pclose($process);
    }
  } else {
    $ps = @popen('sysctl -a', 'rb');
    if (false !== $ps) {
      $output = stream_get_contents($ps);
      preg_match('/hw.ncpu: (\d+)/', $output, $matches);
      if ($matches) {
        $ans = intval($matches[1][0]);
      }
      pclose($ps);
    }
  }  
  return $ans;
}

See also: Single Core CPU Scheduling Algorithm by Using a Priority Queue

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
281 words
Last Post: Teaching Kids Programming - Algorithms to Compute the Range Sum of a Binary Search Tree
Next Post: Design a Binary-Integer-Divisble-By-Three Stream using Math

The Permanent URL is: How to Get Number of CPU Cores using PHP Function (Platform Independent)

One Response

Leave a Reply