class Concurrent::Utility::ProcessorCounter

def compute_physical_processor_count

def compute_physical_processor_count
  ppc = case RbConfig::CONFIG["target_os"]
        when /darwin\d\d/
          IO.popen("/usr/sbin/sysctl -n hw.physicalcpu", &:read).to_i
        when /linux/
          cores = {} # unique physical ID / core ID combinations
          phy   = 0
          IO.read("/proc/cpuinfo").scan(/^physical id.*|^core id.*/) do |ln|
            if ln.start_with?("physical")
              phy = ln[/\d+/]
            elsif ln.start_with?("core")
              cid        = phy + ":" + ln[/\d+/]
              cores[cid] = true if not cores[cid]
            end
          end
          cores.count
        when /mswin|mingw/
          # Get-CimInstance introduced in PowerShell 3 or earlier: https://learn.microsoft.com/en-us/previous-versions/powershell/module/cimcmdlets/get-ciminstance?view=powershell-3.0
          result = run('powershell -command "Get-CimInstance -ClassName Win32_Processor -Property NumberOfCores | Select-Object -Property NumberOfCores"')
          if !result || $?.exitstatus != 0
            # fallback to deprecated wmic for older systems
            result = run("wmic cpu get NumberOfCores")
          end
          if !result || $?.exitstatus != 0
            # Bail out if both commands returned something unexpected
            processor_count
          else
            # powershell: "\nNumberOfCores\n-------------\n            4\n\n\n"
            # wmic:       "NumberOfCores  \n\n4              \n\n\n\n"
            result.scan(/\d+/).map(&:to_i).reduce(:+)
          end
        else
          processor_count
        end
  # fall back to logical count if physical info is invalid
  ppc > 0 ? ppc : processor_count
rescue
  return 1
end