-------------------------- CPU - brand, speed
774156
function getCpu() {

  return new Promise((resolve) => {
    process.nextTick(() => {
      const UNKNOWN = 'unknown';
      let result = {
        manufacturer: UNKNOWN,
        brand: UNKNOWN,
        vendor: '',
        family: '',
        model: '',
        stepping: '',
        revision: '',
        voltage: '',
        speed: '0.00',
        speedmin: '',
        speedmax: '',
        cores: util.cores(),
        physicalCores: util.cores(),
        processors: 1,
        socket: '',
        cache: {}
      };
      if (_darwin) {
        exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min hw.packages hw.physicalcpu_max hw.ncpu', function (error, stdout) {
          // if (!error) {
          let lines = stdout.toString().split('\n');
          const modelline = util.getValue(lines, 'machdep.cpu.brand_string');
          result.brand = modelline.split('@')[0].trim();
          result.speed = modelline.split('@')[1].trim();
          result.speed = parseFloat(result.speed.replace(/GHz+/g, '')).toFixed(2);
          _cpu_speed = result.speed;
          result = cpuBrandManufacturer(result);
          result.speedmin = (util.getValue(lines, 'hw.cpufrequency_min') / 1000000000.0).toFixed(2);
          result.speedmax = (util.getValue(lines, 'hw.cpufrequency_max') / 1000000000.0).toFixed(2);
          result.vendor = util.getValue(lines, 'machdep.cpu.vendor');
          result.family = util.getValue(lines, 'machdep.cpu.family');
          result.model = util.getValue(lines, 'machdep.cpu.model');
          result.stepping = util.getValue(lines, 'machdep.cpu.stepping');
          const countProcessors = util.getValue(lines, 'hw.packages');
          const countCores = util.getValue(lines, 'hw.physicalcpu_max');
          const countThreads = util.getValue(lines, 'hw.ncpu');
          if (countProcessors) {
            result.processors = parseInt(countProcessors) || 1;
          }
          if (countCores && countThreads) {
            result.cores = parseInt(countThreads) || util.cores();
            result.physicalCores = parseInt(countCores) || util.cores();
          }
          // }
          cpuCache().then(res => {
            result.cache = res;
            resolve(result);
          });
        });
      }
      if (_linux) {
        let modelline = '';
        let lines = [];
        if (os.cpus()[0] && os.cpus()[0].model) modelline = os.cpus()[0].model;
        exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) {
          if (!error) {
            lines = stdout.toString().split('\n');
          }
          modelline = util.getValue(lines, 'model name') || modelline;
          result.brand = modelline.split('@')[0].trim();
          result.speed = modelline.split('@')[1] ? parseFloat(modelline.split('@')[1].trim()).toFixed(2) : '0.00';
          if (result.speed === '0.00' && result.brand.indexOf('AMD') > -1) {
            result.speed = getAMDSpeed(result.brand);
          }
          if (result.speed === '0.00') {
            let current = getCpuCurrentSpeedSync();
            if (current.avg !== 0) result.speed = current.avg.toFixed(2);
          }
          _cpu_speed = result.speed;
          result.speedmin = Math.round(parseFloat(util.getValue(lines, 'cpu min mhz').replace(/,/g, '.')) / 10.0) / 100;
          result.speedmin = result.speedmin ? parseFloat(result.speedmin).toFixed(2) : '';
          result.speedmax = Math.round(parseFloat(util.getValue(lines, 'cpu max mhz').replace(/,/g, '.')) / 10.0) / 100;
          result.speedmax = result.speedmax ? parseFloat(result.speedmax).toFixed(2) : '';

          result = cpuBrandManufacturer(result);
          result.vendor = util.getValue(lines, 'vendor id');
          // if (!result.vendor) { result.vendor = util.getValue(lines, 'anbieterkennung'); }
          result.family = util.getValue(lines, 'cpu family');
          // if (!result.family) { result.family = util.getValue(lines, 'prozessorfamilie'); }
          result.model = util.getValue(lines, 'model:');
          // if (!result.model) { result.model = util.getValue(lines, 'modell:'); }
          result.stepping = util.getValue(lines, 'stepping');
          result.revision = util.getValue(lines, 'cpu revision');
          result.cache.l1d = util.getValue(lines, 'l1d cache');
          if (result.cache.l1d) { result.cache.l1d = parseInt(result.cache.l1d) * (result.cache.l1d.indexOf('K') !== -1 ? 1024 : 1); }
          result.cache.l1i = util.getValue(lines, 'l1i cache');
          if (result.cache.l1i) { result.cache.l1i = parseInt(result.cache.l1i) * (result.cache.l1i.indexOf('K') !== -1 ? 1024 : 1); }
          result.cache.l2 = util.getValue(lines, 'l2 cache');
          if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * (result.cache.l2.indexOf('K') !== -1 ? 1024 : 1); }
          result.cache.l3 = util.getValue(lines, 'l3 cache');
          if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * (result.cache.l3.indexOf('K') !== -1 ? 1024 : 1); }

          // socket type
          lines = [];
          exec('export LC_ALL=C; dmidecode –t 4 2>/dev/null | grep "Upgrade: Socket"; unset LC_ALL', function (error2, stdout2) {
            lines = stdout2.toString().split('\n');
            if (lines && lines.length) {
              result.socket = util.getValue(lines, 'Upgrade').replace('Socket', '').trim();
            }

            // # processurs & # threads/core - method 1
            let threadsPerCoreInt = 0;
            lines = [];
            exec('cat /proc/cpuinfo | grep -E "physical id|core id"', function (error2, stdout3) {
              lines = stdout3.toString().split('\n');
              if (lines && lines.length) {
                result.processors = util.countUniqueLines(lines, 'physical id') || 1;
                result.physicalCores = util.countUniqueLines(lines, 'core id') / result.processors;
                if (result.physicalCores) {
                  threadsPerCoreInt = result.cores / result.physicalCores;
                }
              }
              // # threads/core - method 2
              if (threadsPerCoreInt === 0) {
                const threadsPerCore = util.getValue(lines, 'thread(s) per core');
                if (threadsPerCore) {
                  threadsPerCoreInt = parseInt(threadsPerCore, 10);
                  if (!isNaN(threadsPerCoreInt)) {
                    result.physicalCores = result.cores / threadsPerCoreInt;
                  }
                }
              }
              resolve(result);
            });
          });
        });
      }
      if (_freebsd || _openbsd) {
        let modelline = '';
        let lines = [];
        if (os.cpus()[0] && os.cpus()[0].model) modelline = os.cpus()[0].model;
        exec('export LC_ALL=C; dmidecode -t 4 2>/dev/null; dmidecode -t 7 2>/dev/null; unset LC_ALL', function (error, stdout) {
          let cache = [];
          if (!error) {
            const data = stdout.toString().split('# dmidecode');
            const processor = data.length > 0 ? data[1] : '';
            cache = data.length > 1 ? data[2].split('Cache Information') : [];

            lines = processor.split('\n');
          }
          result.brand = modelline.split('@')[0].trim();
          result.speed = modelline.split('@')[1] ? parseFloat(modelline.split('@')[1].trim()).toFixed(2) : '0.00';
          if (result.speed === '0.00' && result.brand.indexOf('AMD') > -1) {
            result.speed = getAMDSpeed(result.brand);
          }
          if (result.speed === '0.00') {
            let current = getCpuCurrentSpeedSync();
            if (current.avg !== 0) result.speed = current.avg.toFixed(2);
          }
          _cpu_speed = result.speed;
          result.speedmin = '';
          result.speedmax = Math.round(parseFloat(util.getValue(lines, 'max speed').replace(/Mhz/g, '')) / 10.0) / 100;
          result.speedmax = result.speedmax ? parseFloat(result.speedmax).toFixed(2) : '';

          result = cpuBrandManufacturer(result);
          result.vendor = util.getValue(lines, 'manufacturer');
          let sig = util.getValue(lines, 'signature');
          sig = sig.split(',');
          for (var i = 0; i < sig.length; i++) {
            sig[i] = sig[i].trim();
          }
          result.family = util.getValue(sig, 'Family', ' ', true);
          result.model = util.getValue(sig, 'Model', ' ', true);
          result.stepping = util.getValue(sig, 'Stepping', ' ', true);
          result.revision = '';
          const voltage = parseFloat(util.getValue(lines, 'voltage'));
          result.voltage = isNaN(voltage) ? '' : voltage.toFixed(2);
          for (let i = 0; i < cache.length; i++) {
            lines = cache[i].split('\n');
            let cacheType = util.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-');
            cacheType = cacheType.length ? cacheType[0] : '';
            const sizeParts = util.getValue(lines, 'Installed Size').split(' ');
            let size = parseInt(sizeParts[0], 10);
            const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb';
            size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1)));
            if (cacheType) {
              if (cacheType === 'l1') {
                result.cache[cacheType + 'd'] = size / 2;
                result.cache[cacheType + 'i'] = size / 2;
              } else {
                result.cache[cacheType] = size;
              }
            }
          }
          // socket type
          result.socket = util.getValue(lines, 'Upgrade').replace('Socket', '').trim();
          // # threads / # cores
          const threadCount = util.getValue(lines, 'thread count').trim();
          const coreCount = util.getValue(lines, 'core count').trim();
          if (coreCount && threadCount) {
            result.cores = threadCount;
            result.physicalCores = coreCount;
          }
          resolve(result);
        });
      }
      if (_sunos) {
        resolve(result);
      }
      if (_windows) {
        try {
          util.wmic('cpu get /value').then((stdout, error) => {
            if (!error) {
              let lines = stdout.split('\r\n');
              let name = util.getValue(lines, 'name', '=') || '';
              if (name.indexOf('@') >= 0) {
                result.brand = name.split('@')[0].trim();
                result.speed = name.split('@')[1].trim();
                result.speed = parseFloat(result.speed.replace(/GHz+/g, '').trim()).toFixed(2);
                _cpu_speed = result.speed;
              } else {
                result.brand = name.trim();
                result.speed = 0;
              }
              result = cpuBrandManufacturer(result);
              result.revision = util.getValue(lines, 'revision', '=');
              result.cache.l1d = 0;
              result.cache.l1i = 0;
              result.cache.l2 = util.getValue(lines, 'l2cachesize', '=');
              result.cache.l3 = util.getValue(lines, 'l3cachesize', '=');
              if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2, 10) * 1024; }
              if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3, 10) * 1024; }
              result.vendor = util.getValue(lines, 'manufacturer', '=');
              result.speedmax = Math.round(parseFloat(util.getValue(lines, 'maxclockspeed', '=').replace(/,/g, '.')) / 10.0) / 100;
              result.speedmax = result.speedmax ? parseFloat(result.speedmax).toFixed(2) : '';
              if (!result.speed && result.brand.indexOf('AMD') > -1) {
                result.speed = getAMDSpeed(result.brand);
              }
              if (!result.speed) {
                result.speed = result.speedmax;
              }

              let description = util.getValue(lines, 'description', '=').split(' ');
              for (let i = 0; i < description.length; i++) {
                if (description[i].toLowerCase().startsWith('family') && (i + 1) < description.length && description[i + 1]) {
                  result.family = description[i + 1];
                }
                if (description[i].toLowerCase().startsWith('model') && (i + 1) < description.length && description[i + 1]) {
                  result.model = description[i + 1];
                }
                if (description[i].toLowerCase().startsWith('stepping') && (i + 1) < description.length && description[i + 1]) {
                  result.stepping = description[i + 1];
                }
              }
              // socket type
              const socketId = util.getValue(lines, 'UpgradeMethod', '=');
              if (socketTypes[socketId]) {
                result.socket = socketTypes[socketId];
              }
              // # threads / # cores
              const countProcessors = util.countUniqueLines(lines, 'Caption');
              const countThreads = util.getValue(lines, 'NumberOfLogicalProcessors', '=');
              const countCores = util.getValue(lines, 'NumberOfCores', '=');
              if (countProcessors) {
                result.processors = parseInt(countProcessors) || 1;
              }
              if (countCores && countThreads) {
                result.cores = parseInt(countThreads) || util.cores();
                result.physicalCores = parseInt(countCores) || util.cores();
              }
            }
            util.wmic('path Win32_CacheMemory get CacheType,InstalledSize,Purpose').then((stdout, error) => {
              if (!error) {
                let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
                lines.forEach(function (line) {
                  if (line !== '') {
                    line = line.trim().split(/\s\s+/);
                    // L1 Instructions
                    if (line[2] === 'L1 Cache' && line[0] === '3') {
                      result.cache.l1i = parseInt(line[1], 10);
                    }
                    // L1 Data
                    if (line[2] === 'L1 Cache' && line[0] === '4') {
                      result.cache.l1d = parseInt(line[1], 10);
                    }
                  }
                });
              }
              resolve(result);
            });
          });
        } catch (e) {
          resolve(result);
        }
      }
    });
  });
}
137998
protected function _cpuinfo()
    {
        if (CommonFunctions::rfts('/proc/cpuinfo', $bufr)) {
            $cpulist = null;
            $raslist = null;

            // sparc
            if (preg_match('/\nCpu(\d+)Bogo\s*:/i', $bufr)) {
                $bufr = preg_replace('/\nCpu(\d+)ClkTck\s*:/i', "\nCpu0ClkTck:", preg_replace('/\nCpu(\d+)Bogo\s*:/i', "\n\nprocessor: $1\nCpu0Bogo:", $bufr));
            } else {
                $bufr = preg_replace('/\nCpu(\d+)ClkTck\s*:/i', "\n\nprocessor: $1\nCpu0ClkTck:", $bufr);
            }

            if (preg_match('/\nprocessor\s*:\s*\d+\r?\nprocessor\s*:\s*\d+/', $bufr)) {
                $bufr = preg_replace('/^(processor\s*:\s*\d+)\r?$/m', "$1\n", $bufr);
            }

            $processors = preg_split('/\s?\n\s?\n/', trim($bufr));

            //first stage
            $_arch = null;
            $_impl = null;
            $_part = null;
            $_hard = null;
            $_revi = null;
            $_cpus = null;
            $_buss = null;
            $procname = null;
            foreach ($processors as $processor) if (!preg_match('/^\s*processor\s*:/mi', $processor)) {
                $details = preg_split("/\n/", $processor, -1, PREG_SPLIT_NO_EMPTY);
                foreach ($details as $detail) {
                    $arrBuff = preg_split('/\s*:\s*/', trim($detail));
                    if ((count($arrBuff) == 2) && (($arrBuff1 = trim($arrBuff[1])) !== '')) {
                        switch (strtolower($arrBuff[0])) {
                        case 'cpu architecture':
                            $_arch = $arrBuff1;
                            break;
                        case 'cpu implementer':
                            $_impl = $arrBuff1;
                            break;
                        case 'cpu part':
                            $_part = $arrBuff1;
                            break;
                        case 'hardware':
                            $_hard = $arrBuff1;
                            break;
                        case 'revision':
                            $_revi = $arrBuff1;
                            break;
                        case 'cpu frequency':
                            if (preg_match('/^(\d+)\s+Hz/i', $arrBuff1, $bufr2)) {
                                $_cpus = round($bufr2[1]/1000000);
                            }
                            break;
                        case 'system bus frequency':
                            if (preg_match('/^(\d+)\s+Hz/i', $arrBuff1, $bufr2)) {
                                $_buss = round($bufr2[1]/1000000);
                            }
                            break;
                        case 'cpu':
                            $procname = $arrBuff1;
                            break;
                        }
                    }
                }
            }

            //second stage
            $cpucount = 0;
            $speedset = false;
            foreach ($processors as $processor) if (preg_match('/^\s*processor\s*:/mi', $processor)) {
                $proc = null;
                $arch = null;
                $impl = null;
                $part = null;
                $dev = new CpuDevice();
                $details = preg_split("/\n/", $processor, -1, PREG_SPLIT_NO_EMPTY);
                foreach ($details as $detail) {
                    $arrBuff = preg_split('/\s*:\s*/', trim($detail));
                    if ((count($arrBuff) == 2) && (($arrBuff1 = trim($arrBuff[1])) !== '')) {
                        switch (strtolower($arrBuff[0])) {
                        case 'processor':
                            $proc = $arrBuff1;
                            if (is_numeric($proc)) {
                                if (strlen($procname)>0) {
                                    $dev->setModel($procname);
                                }
                            } else {
                                $procname = $proc;
                                $dev->setModel($procname);
                            }
                            break;
                        case 'model name':
                        case 'cpu model':
                        case 'cpu type':
                        case 'cpu':
                            $dev->setModel($arrBuff1);
                            break;
                        case 'cpu mhz':
                        case 'clock':
                            if ($arrBuff1 > 0) { //openSUSE fix
                                $dev->setCpuSpeed($arrBuff1);
                                $speedset = true;
                            }
                            break;
                        case 'cycle frequency [hz]':
                            $dev->setCpuSpeed($arrBuff1 / 1000000);
                            $speedset = true;
                            break;
                        case 'cpu0clktck':
                            $dev->setCpuSpeed(hexdec($arrBuff1) / 1000000); // Linux sparc64
                            $speedset = true;
                            break;
                        case 'l3 cache':
                        case 'cache size':
                            $dev->setCache(trim(preg_replace("/[a-zA-Z]/", "", $arrBuff1)) * 1024);
                            break;
                        case 'initial bogomips':
                        case 'bogomips':
                        case 'cpu0bogo':
                            $dev->setBogomips(round($arrBuff1));
                            break;
                        case 'flags':
                            if (preg_match("/ vmx/", $arrBuff1)) {
                                $dev->setVirt("vmx");
                            } elseif (preg_match("/ svm/", $arrBuff1)) {
                                $dev->setVirt("svm");
                            } elseif (preg_match("/ hypervisor/", $arrBuff1)) {
                                $dev->setVirt("hypervisor");
                            }
                            break;
                        case 'i size':
                        case 'd size':
                            if ($dev->getCache() === null) {
                                $dev->setCache($arrBuff1 * 1024);
                            } else {
                                $dev->setCache($dev->getCache() + ($arrBuff1 * 1024));
                            }
                            break;
                        case 'cpu architecture':
                            $arch = $arrBuff1;
                            break;
                        case 'cpu implementer':
                            $impl = $arrBuff1;
                            break;
                        case 'cpu part':
                            $part = $arrBuff1;
                            break;
                        }
                    }
                }
                if ($arch === null) $arch = $_arch;
                if ($impl === null) $impl = $_impl;
                if ($part === null) $part = $_part;


                // sparc64 specific code follows
                // This adds the ability to display the cache that a CPU has
                // Originally made by Sven Blumenstein <bazik@gentoo.org> in 2004
                // Modified by Tom Weustink <freshy98@gmx.net> in 2004
                $sparclist = array('SUNW,UltraSPARC@0,0', 'SUNW,UltraSPARC-II@0,0', 'SUNW,UltraSPARC@1c,0', 'SUNW,UltraSPARC-IIi@1c,0', 'SUNW,UltraSPARC-II@1c,0', 'SUNW,UltraSPARC-IIe@0,0');
                foreach ($sparclist as $name) {
                    if (CommonFunctions::rfts('/proc/openprom/'.$name.'/ecache-size', $buf, 1, 32, false)) {
                        $dev->setCache(base_convert(trim($buf), 16, 10));
                    }
                }
                // sparc64 specific code ends

                // XScale detection code
                if (($arch === "5TE") && ($dev->getBogomips() != null)) {
                    $dev->setCpuSpeed($dev->getBogomips()); //BogoMIPS are not BogoMIPS on this CPU, it's the speed
                    $speedset = true;
                    $dev->setBogomips(null); // no BogoMIPS available, unset previously set BogoMIPS
                }

                if (($dev->getBusSpeed() == 0) && ($_buss !== null)) {
                    $dev->setBusSpeed($_buss);
                }
                if (($dev->getCpuSpeed() == 0) && ($_cpus !== null)) {
                    $dev->setCpuSpeed($_cpus);
                    $speedset = true;
                }

                if ($proc != null) {
                    if (!is_numeric($proc)) {
                        $proc = 0;
                    }
                    // variable speed processors specific code follows
                    if (CommonFunctions::rfts('/sys/devices/system/cpu/cpu'.$proc.'/cpufreq/cpuinfo_cur_freq', $buf, 1, 4096, false)) {
                        $dev->setCpuSpeed(trim($buf) / 1000);
                        $speedset = true;
                    } elseif (CommonFunctions::rfts('/sys/devices/system/cpu/cpu'.$proc.'/cpufreq/scaling_cur_freq', $buf, 1, 4096, false)) {
                        $dev->setCpuSpeed(trim($buf) / 1000);
                        $speedset = true;
                    }
                    if (CommonFunctions::rfts('/sys/devices/system/cpu/cpu'.$proc.'/cpufreq/cpuinfo_max_freq', $buf, 1, 4096, false)) {
                        $dev->setCpuSpeedMax(trim($buf) / 1000);
                    }
                    if (CommonFunctions::rfts('/sys/devices/system/cpu/cpu'.$proc.'/cpufreq/cpuinfo_min_freq', $buf, 1, 4096, false)) {
                        $dev->setCpuSpeedMin(trim($buf) / 1000);
                    }
                    // variable speed processors specific code ends
                    if (PSI_LOAD_BAR) {
                            $dev->setLoad($this->_parseProcStat('cpu'.$proc));
                    }
/*
                    if (CommonFunctions::rfts('/proc/acpi/thermal_zone/THRM/temperature', $buf, 1, 4096, false)
                       &&  preg_match("/(\S+)\sC$/", $buf, $value)) {
                        $dev->setTemp(value[1]);
                    }
*/
                    if (($arch !== null) && ($impl !== null) && ($part !== null)) {
                        if (($impl === '0x41')
                           && (($_hard === 'BCM2708') || ($_hard === 'BCM2835') || ($_hard === 'BCM2709') || ($_hard === 'BCM2836') || ($_hard === 'BCM2710') || ($_hard === 'BCM2837'))
                           && ($_revi !== null)) { // Raspberry Pi detection (instead of 'cat /proc/device-tree/model')
                            if ($raslist === null) $raslist = @parse_ini_file(PSI_APP_ROOT."/data/raspberry.ini", true);
                            if ($raslist && !preg_match('/[^0-9a-f]/', $_revi)) {
                                if (($revidec = hexdec($_revi)) & 0x800000) {
                                    if ($this->sys->getMachine() === '') {
                                        $manufacturer = ($revidec >> 16) & 15;
                                        if (isset($raslist['manufacturer'][$manufacturer])) {
                                            $manuf = ' '.$raslist['manufacturer'][$manufacturer];
                                        } else {
                                            $manuf = '';
                                        }
                                        $model = ($revidec >> 4) & 255;
                                        if (isset($raslist['model'][$model])) {
                                            $this->sys->setMachine('Raspberry Pi '.$raslist['model'][$model].' (PCB 1.'.($revidec & 15).$manuf.')');
                                        } else {
                                            $this->sys->setMachine('Raspberry Pi (PCB 1.'.($revidec & 15).$manuf.')');
                                        }
                                    }
                                } else {
                                    if ($this->sys->getMachine() === '') {
                                        if (isset($raslist['old'][$revidec & 0x7fffff])) {
                                            $this->sys->setMachine('Raspberry Pi '.$raslist['old'][$revidec & 0x7fffff]);
                                        } else {
                                            $this->sys->setMachine('Raspberry Pi');
                                        }
                                    }
                                }
                            }
                        } elseif (($_hard !== null) && ($this->sys->getMachine() === '')) { // other ARM hardware
                            $this->sys->setMachine($_hard);
                        }
                        if ($cpulist === null) $cpulist = @parse_ini_file(PSI_APP_ROOT."/data/cpus.ini", true);
                        if ($cpulist && (isset($cpulist['cpu'][$cpuimplpart = strtolower($impl.','.$part)]))) {
                            if (($cpumodel = $dev->getModel()) !== '') {
                                $dev->setModel($cpumodel.' - '.$cpulist['cpu'][$cpuimplpart]);
                            } else {
                                $dev->setModel($cpulist['cpu'][$cpuimplpart]);
                            }
                        }
                    } elseif (($_hard !== null) && ($this->sys->getMachine() === '')) { // other hardware
                        $this->sys->setMachine($_hard);
                    }

                    if ($dev->getModel() === "") {
                        $dev->setModel("unknown");
                    }
                    $cpucount++;
                    $this->sys->setCpus($dev);
                }
            }
            $cpudevices = glob('/sys/devices/system/cpu/cpu*/uevent', GLOB_NOSORT);
            if (is_array($cpudevices) && (($cpustopped = count($cpudevices)-$cpucount) > 0)) {
                for (; $cpustopped > 0; $cpustopped--) {
                    $dev = new CpuDevice();
                    $dev->setModel("stopped");
                    if ($speedset) {
                        $dev->setCpuSpeed(-1);
                    }
                    $this->sys->setCpus($dev);
                }
            }
        }
    }
200492
public function getCPU()
    {

        // Time?
        if (!empty($this->settings['timer'])) {
            $t = new Timer('CPUs');
        }

        // Store them here
        $cpus = [];

        // Stuff it with identical cpus
        for ($i = 0; $i < $this->sysctl['hw.ncpu']; ++$i) {

            // Save each
            $cpus[] = array(
                'Model' => $this->sysctl['hw.model'],
                'MHz' => $this->sysctl['hw.clockrate'],
            );
        }

        // Return
        return $cpus;
    }
1271615
protected void parseCpuInfo(String[] cpuInfoFile) throws IOException {
    int numCpu = 0;
    double cpuTotalGHz = 0;
    for (String line : cpuInfoFile) {
      if (line.startsWith("processor")) {
        numCpu++;
      }
      if (line.startsWith("cpu MHz")) {
        cpuTotalGHz += Double.parseDouble(line.split(":")[1].trim()) / 1000d;
      }
    }
    ttUtilization.setNumCpu(numCpu);
    ttUtilization.setCpuTotalGHz(cpuTotalGHz);
  }
173605
function num_of_cpus() {
  try {
    if(process.env['OMP_NUM_THREADS']) {
      return process.env['OMP_NUM_THREADS'];
    }

    return Math.ceil(jsonConfig.info.limits.cpu);
  } catch (err) {
    throw new Error('Could not get number of cpus');
  }
}
854108
def get_cpu_info(self):
        
        info = snap7.snap7types.S7CpuInfo()
        result = self.library.Cli_GetCpuInfo(self.pointer, byref(info))
        check_error(result, context="client")
        return info
831609
private function getCpu(): array
	{
		$result = [];
		$cpuInfo = $this->readFile('/proc/cpuinfo');
		if ($cpuInfo) {
			$processors = preg_split('/\s?\n\s?\n/', trim($cpuInfo));
			$procname = null;
			foreach ($processors as $processor) {
				$cpu = new Obj;
				$proc = null;
				$arch = null;
				$details = preg_split("/\n/", $processor, -1, PREG_SPLIT_NO_EMPTY);
				foreach ($details as $detail) {
					$arrBuff = preg_split('/\s*:\s*/', trim($detail));
					if (count($arrBuff) == 2) {
						switch (strtolower($arrBuff[0])) {
							case 'processor':
								$proc = trim($arrBuff[1]);
								if (is_numeric($proc)) {
									if ($procname !== null && strlen($procname) > 0) {
										$cpu->model = $procname;
									}
								} else {
									$procname = $proc;
									$cpu->model = $procname;
								}
								break;
							case 'model name':
							case 'cpu model':
							case 'cpu type':
							case 'cpu':
								$cpu->model = $arrBuff[1];
								break;
							case 'cpu mhz':
							case 'clock':
								if ($arrBuff[1] > 0) { //openSUSE fix
									$cpu->speed = $arrBuff[1] * 1000 * 1000;
								}
								break;
							case 'cycle frequency [hz]':
								$cpu->speed = $arrBuff[1] * 1000 * 1000;
								break;
							case 'cpu0clktck':
								$cpu->speed = hexdec($arrBuff[1] * 1000 * 1000);
								break;
							case 'l2 cache':
							case 'cache size':
								$cpu->cache = ((float) preg_replace("/[a-zA-Z]/", "", $arrBuff[1])) * 1024;
								break;
							case 'initial bogomips':
							case 'bogomips':
							case 'cpu0bogo':
								$cpu->bogomips = $arrBuff[1];
								break;
							case 'i size':
							case 'd size':
								if ($cpu->cache === null) {
									$cpu->cache = $arrBuff[1] * 1024;
								} else {
									$cpu->cache = $cpu->cache + ($arrBuff[1] * 1024);
								}
								break;
							case 'cpu architecture':
								$arch = trim($arrBuff[1]);
								break;
						}
					}
				}

				// sparc64 specific code follows
				// This adds the ability to display the cache that a CPU has
				// Originally made by Sven Blumenstein <bazik@gentoo.org> in 2004
				// Modified by Tom Weustink <freshy98@gmx.net> in 2004
				$sparclist = array('SUNW,UltraSPARC@0,0', 'SUNW,UltraSPARC-II@0,0', 'SUNW,UltraSPARC@1c,0', 'SUNW,UltraSPARC-IIi@1c,0', 'SUNW,UltraSPARC-II@1c,0', 'SUNW,UltraSPARC-IIe@0,0');
				foreach ($sparclist as $name) {
					$str = $this->readFile('/proc/openprom/' . $name . '/ecache-size');
					if ($str) {
						$cpu->cache = base_convert($str, 16, 10);
					}
				}

				// sparc64 specific code ends
				// XScale detection code
				if (($arch === "5TE") && ($cpu->bogomips != null)) {
					$cpu->speed = $cpu->bogomips; //BogoMIPS are not BogoMIPS on this CPU, it's the speed
					$cpu->bogomips = null; // no BogoMIPS available, unset previously set BogoMIPS
				}

				if ($proc != null) {
					if (!is_numeric($proc)) {
						$proc = 0;
					}
					// variable speed processors specific code follows
					if ($str = $this->readFile('/sys/devices/system/cpu/cpu' . $proc . '/cpufreq/cpuinfo_cur_freq')) {
						$cpu->speed = ((float) $str) * 1000;
					} elseif ($str = $this->readFile('/sys/devices/system/cpu/cpu' . $proc . '/cpufreq/scaling_cur_freq')) {
						$cpu->speed = ((float) $str) * 1000;
					}
					if ($str = $this->readFile('/sys/devices/system/cpu/cpu' . $proc . '/cpufreq/cpuinfo_max_freq')) {
						$cpu->speedMax = ((float) $str) * 1000;
					}
					if ($str = $this->readFile('/sys/devices/system/cpu/cpu' . $proc . '/cpufreq/cpuinfo_min_freq')) {
						$cpu->speedMin = ((float) $str) * 1000;
					}
					if ($str = $this->readFile('/proc/acpi/thermal_zone/THRM/temperature')) {
						$cpu->temperature = substr($str, 25, 2);
					}
				}

				$cpu->usage = null;
				$result[] = $cpu;
			}


			// CPU usage
			$command = "grep 'cpu' /proc/stat";
			$cpuStats1 = $this->readCommandAsArray($command, "\n");
			sleep(1);
			$cpuStats2 = $this->readCommandAsArray($command, "\n");

			$counter = 0;
			for ($i = 0; $i < count($cpuStats1); $i++) {
				if (preg_match('/cpu[0-9]{1,2}/', $cpuStats1[$i]) > 0) {
					$stats1 = explode(' ', $cpuStats1[$i]);
					$stats2 = explode(' ', $cpuStats2[$i]);

					$prevIdle = $stats1[4] + $stats1[5];
					$idle = $stats2[4] + $stats2[5];
					$prevNonIdle = $stats1[1] + $stats1[2] + $stats1[3] + $stats1[6] + $stats1[7] + $stats1[8];
					$nonIdle = $stats2[1] + $stats2[2] + $stats2[3] + $stats2[6] + $stats2[7] + $stats2[8];
					$prevTotal = $prevIdle + $prevNonIdle;
					$total = $idle + $nonIdle;

					$result[$counter++]->usage = (float) (($total - $prevTotal) - ($idle - $prevIdle)) / ($total - $prevTotal) * 100;
				}
			}
		}
		return $result;
	}
712197
private double percentageToGHz(double cpuUsage) {
    cpuUsage /= 100;
    cpuUsage /= ttUtilization.getNumCpu();
    cpuUsage *= ttUtilization.getCpuTotalGHz();
    return cpuUsage;
  }
1289356
def cpuinfo():
    ''' 

    '''

    cpuinfo=OrderedDict()
    procinfo=OrderedDict()

    nprocs = 0
    with open('/proc/cpuinfo') as f:
        for line in f:
            if not line.strip():
                # end of one processor
                cpuinfo['proc%s' % nprocs] = procinfo
                nprocs=nprocs+1
                # Reset
                procinfo=OrderedDict()
            else:
                if len(line.split(':')) == 2:
                    procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()
                else:
                    procinfo[line.split(':')[0].strip()] = ''
            
    return cpuinfo
293747
def _get_cpu_info_from_wmic():
	'''
	
	'''

	try:
		# Just return {} if not Windows or there is no wmic
		if not DataSource.is_windows or not DataSource.has_wmic():
			return {}

		returncode, output = DataSource.wmic_cpu()
		if output == None or returncode != 0:
			return {}

		# Break the list into key values pairs
		value = output.split("\n")
		value = [s.rstrip().split('=') for s in value if '=' in s]
		value = {k: v for k, v in value if v}

		# Get the advertised MHz
		processor_brand = value.get('Name')
		hz_advertised, scale_advertised = _parse_cpu_brand_string(processor_brand)

		# Get the actual MHz
		hz_actual = value.get('CurrentClockSpeed')
		scale_actual = 6
		if hz_actual:
			hz_actual = _to_decimal_string(hz_actual)

		# Get cache sizes
		l2_cache_size = value.get('L2CacheSize')
		if l2_cache_size:
			l2_cache_size = l2_cache_size + ' KB'

		l3_cache_size = value.get('L3CacheSize')
		if l3_cache_size:
			l3_cache_size = l3_cache_size + ' KB'

		# Get family, model, and stepping
		family, model, stepping = '', '', ''
		description = value.get('Description') or value.get('Caption')
		entries = description.split(' ')

		if 'Family' in entries and entries.index('Family') < len(entries)-1:
			i = entries.index('Family')
			family = int(entries[i + 1])

		if 'Model' in entries and entries.index('Model') < len(entries)-1:
			i = entries.index('Model')
			model = int(entries[i + 1])

		if 'Stepping' in entries and entries.index('Stepping') < len(entries)-1:
			i = entries.index('Stepping')
			stepping = int(entries[i + 1])

		info = {
			'vendor_id_raw' : value.get('Manufacturer'),
			'brand_raw' : processor_brand,

			'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale_advertised),
			'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, scale_actual),
			'hz_advertised' : _hz_short_to_full(hz_advertised, scale_advertised),
			'hz_actual' : _hz_short_to_full(hz_actual, scale_actual),

			'l2_cache_size' : l2_cache_size,
			'l3_cache_size' : l3_cache_size,

			'stepping' : stepping,
			'model' : model,
			'family' : family,
		}

		info = {k: v for k, v in info.items() if v}
		return info
	except:
		#raise # NOTE: To have this throw on error, uncomment this line
		return {}
1368324
def _cpu(self):
        """"""
        value = int(psutil.cpu_percent())
        set_metric("cpu", value, category=self.category)
        gauge("cpu", value)
143724
private function _buildHardware()
    {
        $hardware = $this->_xml->addChild('Hardware');
        if ($this->_sys->getMachine() != "") {
            $hardware->addAttribute('Name', $this->_sys->getMachine());
        }
        $pci = null;
        foreach (System::removeDupsAndCount($this->_sys->getPciDevices()) as $dev) {
            if ($pci === null) $pci = $hardware->addChild('PCI');
            $tmp = $pci->addChild('Device');
            $tmp->addAttribute('Name', $dev->getName());
            if (defined('PSI_SHOW_DEVICES_INFOS') && PSI_SHOW_DEVICES_INFOS) {
                if ($dev->getManufacturer() !== null) {
                    $tmp->addAttribute('Manufacturer', $dev->getManufacturer());
                }
                if ($dev->getProduct() !== null) {
                    $tmp->addAttribute('Product', $dev->getProduct());
                }
            }
            if ($dev->getCount() > 1) {
                $tmp->addAttribute('Count', $dev->getCount());
            }
        }
        $usb = null;
        foreach (System::removeDupsAndCount($this->_sys->getUsbDevices()) as $dev) {
            if ($usb === null) $usb = $hardware->addChild('USB');
            $tmp = $usb->addChild('Device');
            $tmp->addAttribute('Name', $dev->getName());
            if (defined('PSI_SHOW_DEVICES_INFOS') && PSI_SHOW_DEVICES_INFOS) {
                if ($dev->getManufacturer() !== null) {
                    $tmp->addAttribute('Manufacturer', $dev->getManufacturer());
                }
                if ($dev->getProduct() !== null) {
                    $tmp->addAttribute('Product', $dev->getProduct());
                }
                if (defined('PSI_SHOW_DEVICES_SERIAL') && PSI_SHOW_DEVICES_SERIAL && ($dev->getSerial() !== null)) {
                    $tmp->addAttribute('Serial', $dev->getSerial());
                }
            }
            if ($dev->getCount() > 1) {
                $tmp->addAttribute('Count', $dev->getCount());
            }
        }
        $ide = null;
        foreach (System::removeDupsAndCount($this->_sys->getIdeDevices()) as $dev) {
            if ($ide === null) $ide = $hardware->addChild('IDE');
            $tmp = $ide->addChild('Device');
            $tmp->addAttribute('Name', $dev->getName());
            if (defined('PSI_SHOW_DEVICES_INFOS') && PSI_SHOW_DEVICES_INFOS) {
                if ($dev->getCapacity() !== null) {
                    $tmp->addAttribute('Capacity', $dev->getCapacity());
                }
                if (defined('PSI_SHOW_DEVICES_SERIAL') && PSI_SHOW_DEVICES_SERIAL && ($dev->getSerial() !== null)) {
                    $tmp->addAttribute('Serial', $dev->getSerial());
                }
            }
            if ($dev->getCount() > 1) {
                $tmp->addAttribute('Count', $dev->getCount());
            }
        }
        $scsi = null;
        foreach (System::removeDupsAndCount($this->_sys->getScsiDevices()) as $dev) {
            if ($scsi === null) $scsi = $hardware->addChild('SCSI');
            $tmp = $scsi->addChild('Device');
            $tmp->addAttribute('Name', $dev->getName());
            if (defined('PSI_SHOW_DEVICES_INFOS') && PSI_SHOW_DEVICES_INFOS) {
                if ($dev->getCapacity() !== null) {
                    $tmp->addAttribute('Capacity', $dev->getCapacity());
                }
                if (defined('PSI_SHOW_DEVICES_SERIAL') && PSI_SHOW_DEVICES_SERIAL && ($dev->getSerial() !== null)) {
                    $tmp->addAttribute('Serial', $dev->getSerial());
                }
            }
            if ($dev->getCount() > 1) {
                $tmp->addAttribute('Count', $dev->getCount());
            }
        }
        $nvme = null;
        foreach (System::removeDupsAndCount($this->_sys->getNvmeDevices()) as $dev) {
            if ($nvme === null) $nvme = $hardware->addChild('NVMe');
            $tmp = $nvme->addChild('Device');
            $tmp->addAttribute('Name', $dev->getName());
            if (defined('PSI_SHOW_DEVICES_INFOS') && PSI_SHOW_DEVICES_INFOS) {
                if ($dev->getCapacity() !== null) {
                    $tmp->addAttribute('Capacity', $dev->getCapacity());
                }
                if (defined('PSI_SHOW_DEVICES_SERIAL') && PSI_SHOW_DEVICES_SERIAL && ($dev->getSerial() !== null)) {
                    $tmp->addAttribute('Serial', $dev->getSerial());
                }
            }
            if ($dev->getCount() > 1) {
                $tmp->addAttribute('Count', $dev->getCount());
            }
        }
        $tb = null;
        foreach (System::removeDupsAndCount($this->_sys->getTbDevices()) as $dev) {
            if ($tb === null) $tb = $hardware->addChild('TB');
            $tmp = $tb->addChild('Device');
            $tmp->addAttribute('Name', $dev->getName());
            if ($dev->getCount() > 1) {
                $tmp->addAttribute('Count', $dev->getCount());
            }
        }
        $i2c = null;
        foreach (System::removeDupsAndCount($this->_sys->getI2cDevices()) as $dev) {
            if ($i2c === null) $i2c = $hardware->addChild('I2C');
            $tmp = $i2c->addChild('Device');
            $tmp->addAttribute('Name', $dev->getName());
            if ($dev->getCount() > 1) {
                $tmp->addAttribute('Count', $dev->getCount());
            }
        }

        $cpu = null;
        foreach ($this->_sys->getCpus() as $oneCpu) {
            if ($cpu === null) $cpu = $hardware->addChild('CPU');
            $tmp = $cpu->addChild('CpuCore');
            $tmp->addAttribute('Model', $oneCpu->getModel());
            if ($oneCpu->getCpuSpeed() !== 0) {
                $tmp->addAttribute('CpuSpeed', max($oneCpu->getCpuSpeed(), 0));
            }
            if ($oneCpu->getCpuSpeedMax() !== 0) {
                $tmp->addAttribute('CpuSpeedMax', $oneCpu->getCpuSpeedMax());
            }
            if ($oneCpu->getCpuSpeedMin() !== 0) {
                $tmp->addAttribute('CpuSpeedMin', $oneCpu->getCpuSpeedMin());
            }
/*
            if ($oneCpu->getTemp() !== null) {
                $tmp->addAttribute('CpuTemp', $oneCpu->getTemp());
            }
*/
            if ($oneCpu->getBusSpeed() !== null) {
                $tmp->addAttribute('BusSpeed', $oneCpu->getBusSpeed());
            }
            if ($oneCpu->getCache() !== null) {
                $tmp->addAttribute('Cache', $oneCpu->getCache());
            }
            if ($oneCpu->getVirt() !== null) {
                $tmp->addAttribute('Virt', $oneCpu->getVirt());
            }
            if ($oneCpu->getBogomips() !== null) {
                $tmp->addAttribute('Bogomips', $oneCpu->getBogomips());
            }
            if ($oneCpu->getLoad() !== null) {
                $tmp->addAttribute('Load', $oneCpu->getLoad());
            }
        }
    }
1149310
def _processor(self):
        """"""
        self.store.cleanup(self._config.timeout)
        self._load()
224266
def cpuinfo():
    """"""
    f = open("/proc/cpuinfo")
    hwinfo = {}
    for line in f.readlines():
        cpul = line.split(":")
        name = cpul[0].strip()
        if (len(cpul) > 1):
            val = cpul[1].strip()
        if (name == "model name"):
            hwinfo["CPU"] = val
        elif (name == "cpu MHz"):
            hwinfo["MHz"] = int(round(float(val)))
    f.close()
    return hwinfo
331341
def _supports_avx():
    """"""
    if os.path.exists("/proc/cpuinfo"):
        with open("/proc/cpuinfo") as in_handle:
            for line in in_handle:
                if line.startswith("flags") and line.find("avx") > 0:
                    return True
518023
def set_mem_per_proc(self, mem_mb):
        """"""
        super().set_mem_per_proc(mem_mb)
        self.qparams["mem_per_cpu"] = self.mem_per_proc
350370
def usable_cpu_count():
    
    try:
        result = len(os.sched_getaffinity(0))
    except AttributeError:
        try:
            result = len(psutil.Process().cpu_affinity())
        except AttributeError:
            result = os.cpu_count()
    return result