System.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Support;
  12. class System
  13. {
  14. /**
  15. * Get the number of CPU cores.
  16. */
  17. public static function getCpuCoresNum(): int
  18. {
  19. if (function_exists('swoole_cpu_num')) {
  20. return swoole_cpu_num();
  21. }
  22. $num = 1;
  23. if (is_file('/proc/cpuinfo')) {
  24. $cpuinfo = file_get_contents('/proc/cpuinfo');
  25. preg_match_all('/^processor/m', $cpuinfo, $matches);
  26. $num = count($matches[0]);
  27. } elseif (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
  28. $process = @popen('wmic cpu get NumberOfCores', 'rb');
  29. if ($process !== false) {
  30. fgets($process);
  31. $num = intval(fgets($process));
  32. pclose($process);
  33. }
  34. } else {
  35. $process = @popen('sysctl -a', 'rb');
  36. if ($process !== false) {
  37. $output = stream_get_contents($process);
  38. preg_match('/hw.ncpu: (\d+)/', $output, $matches);
  39. if ($matches) {
  40. $num = intval($matches[1][0]);
  41. }
  42. pclose($process);
  43. }
  44. }
  45. return $num;
  46. }
  47. }