Skip to content

Instantly share code, notes, and snippets.

@rdlowrey
Created February 20, 2015 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdlowrey/c26dede388f26515f82b to your computer and use it in GitHub Desktop.
Save rdlowrey/c26dede388f26515f82b to your computer and use it in GitHub Desktop.
OS-generalized CPU counting
<?php
function countCpuCores() {
$os = (stripos(PHP_OS, "WIN") === 0) ? "win" : strtolower(trim(shell_exec("uname")));
switch ($os) {
case "win":
$cmd = "wmic cpu get NumberOfCores";
break;
case "linux":
$cmd = "cat /proc/cpuinfo | grep processor | wc -l";
break;
case "freebsd":
$cmd = "sysctl -a | grep 'hw.ncpu' | cut -d ':' -f2";
break;
case "darwin":
$cmd = "sysctl -a | grep 'hw.ncpu:' | awk '{ print $2 }'";
break;
default:
$cmd = NULL;
}
$execResult = $cmd ? shell_exec($cmd) : 1;
if ($os === 'win') {
$execResult = explode("\n", $execResult)[1];
}
$cores = intval(trim($execResult));
return $cores;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment