Skip to content

Instantly share code, notes, and snippets.

@ezzatron
Created October 28, 2011 03:53
Show Gist options
  • Save ezzatron/1321581 to your computer and use it in GitHub Desktop.
Save ezzatron/1321581 to your computer and use it in GitHub Desktop.
Function to detect number of CPUs in PHP
<?php
/**
* Copyright © 2011 Erin Millard
*/
/**
* Returns the number of available CPU cores
*
* Should work for Linux, Windows, Mac & BSD
*
* @return integer
*/
function num_cpus()
{
$numCpus = 1;
if (is_file('/proc/cpuinfo'))
{
$cpuinfo = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpuinfo, $matches);
$numCpus = count($matches[0]);
}
else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3)))
{
$process = @popen('wmic cpu get NumberOfCores', 'rb');
if (false !== $process)
{
fgets($process);
$numCpus = intval(fgets($process));
pclose($process);
}
}
else
{
$process = @popen('sysctl -a', 'rb');
if (false !== $process)
{
$output = stream_get_contents($process);
preg_match('/hw.ncpu: (\d+)/', $output, $matches);
if ($matches)
{
$numCpus = intval($matches[1][0]);
}
pclose($process);
}
}
return $numCpus;
}
echo num_cpus().PHP_EOL;
@duzun
Copy link

duzun commented Sep 30, 2015

I would cache the number of CPUs returned, at least with static:

    static $numCpus;
    if ( !isset($numCpus) ) {
    ...
    }
    return $numCpus;

@adduc
Copy link

adduc commented Mar 24, 2016

@ezzatron Is there a license (MIT, GPLv3, etc.) for this piece of code?

@robinkanters
Copy link

@duzun then at least reduce nesting a bit:

static $numCpus;
if (isset($numCpus))
    return $numCpus;

... // OP's code

return $numCpus;

@andrerom
Copy link

andrerom commented Oct 16, 2017

For something under Apache license there is always Zeta Components SystemInfo: https://github.com/zetacomponents/SystemInformation/blob/master/src/info.php#L65-L73

@divinity76
Copy link

@adduc just made a copyLEFT version, you can fork it and add whatever license you'd like, https://gist.github.com/divinity76/01ef9ca99c111565a72d3a8a6e42f7fb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment