-------------------------- CPU - current speed - in GHz
510388
function getCpuCurrentSpeedSync() {

  let cpus = os.cpus();
  let minFreq = 999999999;
  let maxFreq = 0;
  let avgFreq = 0;
  let cores = [];

  if (cpus.length) {
    for (let i in cpus) {
      if (cpus.hasOwnProperty(i)) {
        avgFreq = avgFreq + cpus[i].speed;
        if (cpus[i].speed > maxFreq) maxFreq = cpus[i].speed;
        if (cpus[i].speed < minFreq) minFreq = cpus[i].speed;
      }
      cores.push(parseFloat(((cpus[i].speed + 1) / 1000).toFixed(2)));
    }
    avgFreq = avgFreq / cpus.length;
    return {
      min: parseFloat(((minFreq + 1) / 1000).toFixed(2)),
      max: parseFloat(((maxFreq + 1) / 1000).toFixed(2)),
      avg: parseFloat(((avgFreq + 1) / 1000).toFixed(2)),
      cores: cores
    };
  } else {
    return {
      min: 0,
      max: 0,
      avg: 0,
      cores: cores
    };
  }
}
64145
protected function _cpuinfo()
    {
        if (CommonFunctions::rfts('/proc/cpuinfo', $bufr, 0, 4096, false)) {
            $processors = preg_split('/\s?\n\s?\n/', trim($bufr));
            foreach ($processors as $processor) {
                $_n = ""; $_f = ""; $_m = ""; $_s = "";
                $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) {
                        switch (strtolower($arrBuff[0])) {
                        case 'model name':
                            $_n = $arrBuff[1];
                            break;
                        case 'cpu mhz':
                            $dev->setCpuSpeed($arrBuff[1]);
                            break;
                        case 'cpu family':
                            $_f = $arrBuff[1];
                            break;
                        case 'model':
                            $_m = $arrBuff[1];
                            break;
                        case 'stepping':
                            $_s = $arrBuff[1];
                            break;
                        case 'flags':
                            if (preg_match("/ vmx/", $arrBuff[1])) {
                                $dev->setVirt("vmx");
                            } elseif (preg_match("/ svm/", $arrBuff[1])) {
                                $dev->setVirt("svm");
                            }
                        break;
                        }
                    }
                }
                if ($_n == "") $_n="CPU";
                if ($_f != "") $_n.=" Family ".$_f;
                if ($_m != "") $_n.=" Model ".$_m;
                if ($_s != "") $_n.=" Stepping ".$_s;
                $dev->SetModel($_n);
                $this->sys->setCpus($dev);
            }
        } else
        foreach ($this->readdmesg() as $line) {
            if (preg_match('/kernel: (CPU .*) freq (.*) MHz/', $line, $ar_buf)) {
                $dev = new CpuDevice();
                $dev->setModel($ar_buf[1]);
                $dev->setCpuSpeed($ar_buf[2]);
                $this->sys->setCpus($dev);
            }
        }
    }
967899
def _get_cpu_info_from_lscpu():
	'''
	
	'''
	try:
		if not DataSource.has_lscpu():
			return {}

		returncode, output = DataSource.lscpu()
		if returncode != 0:
			return {}

		info = {}

		new_hz = _get_field(False, output, None, None, 'CPU max MHz', 'CPU MHz')
		if new_hz:
			new_hz = _to_decimal_string(new_hz)
			scale = 6
			info['hz_advertised_friendly'] = _hz_short_to_friendly(new_hz, scale)
			info['hz_actual_friendly'] = _hz_short_to_friendly(new_hz, scale)
			info['hz_advertised'] = _hz_short_to_full(new_hz, scale)
			info['hz_actual'] = _hz_short_to_full(new_hz, scale)

		vendor_id = _get_field(False, output, None, None, 'Vendor ID')
		if vendor_id:
			info['vendor_id_raw'] = vendor_id

		brand = _get_field(False, output, None, None, 'Model name')
		if brand:
			info['brand_raw'] = brand

		family = _get_field(False, output, None, None, 'CPU family')
		if family and family.isdigit():
			info['family'] = int(family)

		stepping = _get_field(False, output, None, None, 'Stepping')
		if stepping and stepping.isdigit():
			info['stepping'] = int(stepping)

		model = _get_field(False, output, None, None, 'Model')
		if model and model.isdigit():
			info['model'] = int(model)

		l1_data_cache_size = _get_field(False, output, None, None, 'L1d cache')
		if l1_data_cache_size:
			info['l1_data_cache_size'] = _to_friendly_bytes(l1_data_cache_size)

		l1_instruction_cache_size = _get_field(False, output, None, None, 'L1i cache')
		if l1_instruction_cache_size:
			info['l1_instruction_cache_size'] = _to_friendly_bytes(l1_instruction_cache_size)

		l2_cache_size = _get_field(False, output, None, None, 'L2 cache')
		if l2_cache_size:
			info['l2_cache_size'] = _to_friendly_bytes(l2_cache_size)

		l3_cache_size = _get_field(False, output, None, None, 'L3 cache')
		if l3_cache_size:
			info['l3_cache_size'] = _to_friendly_bytes(l3_cache_size)

		# Flags
		flags = _get_field(False, output, None, None, 'flags', 'Features')
		if flags:
			flags = flags.split()
			flags.sort()
			info['flags'] = flags

		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 {}
1355056
def get_available_frequencies(self):
        '''
        
        '''
        fpath = path.join("cpu0","cpufreq","scaling_available_frequencies")
        data = self.__read_cpu_file(fpath).rstrip("\n").split()
        return data
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;
	}
1157302
private void process(double[] data, double min, double max, KernelDensityFunction kernel, int window, double epsilon) {
    dens = new double[data.length];
    var = new double[data.length];

    // This is the desired bandwidth of the kernel.
    double halfwidth = ((max - min) / window) * .5;

    for (int current = 0; current < data.length; current++) {
      double value = 0.0;
      for (int i = current; i >= 0; i--) {
        double delta = Math.abs(data[i] - data[current]) / halfwidth;
        final double contrib = kernel.density(delta);
        value += contrib;
        if (contrib < epsilon) {
          break;
        }
      }
      for (int i = current + 1; i < data.length; i++) {
        double delta = Math.abs(data[i] - data[current]) / halfwidth;
        final double contrib = kernel.density(delta);
        value += contrib;
        if (contrib < epsilon) {
          break;
        }
      }
      double realwidth = (Math.min(data[current] + halfwidth, max) - Math.max(min, data[current] - halfwidth));
      double weight = realwidth / (2 * halfwidth);
      dens[current] = value / (data.length * realwidth * .5);
      var[current] = 1 / weight;
    }
  }
1088124
private function _cpuinfo()
    {
        $ncpu = 0;
        $tcpu = "";
        $vcpu = "";
        $ccpu = "";
        $scpu = "";
        foreach ($this->readaixdata() as $line) {
            if (preg_match("/^Number Of Processors:\s+(\d+)/", $line, $ar_buf)) {
                $ncpu = $ar_buf[1];
            }
            if (preg_match("/^Processor Type:\s+(.+)/", $line, $ar_buf)) {
                $tcpu = $ar_buf[1];
            }
            if (preg_match("/^Processor Version:\s+(.+)/", $line, $ar_buf)) {
                $vcpu = $ar_buf[1];
            }
            if (preg_match("/^CPU Type:\s+(.+)/", $line, $ar_buf)) {
                $ccpu = $ar_buf[1];
            }
            if (preg_match("/^Processor Clock Speed:\s+(\d+)\s/", $line, $ar_buf)) {
                $scpu = $ar_buf[1];
            }
        }
        for ($i = 0; $i < $ncpu; $i++) {
            $dev = new CpuDevice();
            if (trim($tcpu) != "") {
                $cpu = trim($tcpu);
                if (trim($vcpu) != "") $cpu .= " ".trim($vcpu);
                if (trim($ccpu) != "") $cpu .= " ".trim($ccpu);
                $dev->setModel($cpu);
            }
            if (trim($scpu) != "") {
                $dev->setCpuSpeed(trim($scpu));
            }
            $this->sys->setCpus($dev);
        }
    }
749552
protected function cpu_info()
    {

        $this->cpu_info = array();
        if (!stristr(PHP_OS, 'win')) {
            exec("cat /proc/cpuinfo", $output);
            foreach ($output as $line) {
                $parts = explode(':', $line);

                if (empty($parts[0])) continue;

                $this->cpu_info[trim($parts[0])] = (!empty($parts[1])) ? trim($parts[1]) : null;
            }
        }

        return true;
    }
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
1159758
def checkPerformance(self) -> Optional[bool]:
        
        logger.trace("{} checking its performance".format(self))

        # Move ahead only if the node has synchronized its state with other
        # nodes
        if not self.isParticipating:
            return

        if self.view_change_in_progress:
            return

        if not self._update_new_ordered_reqs_count():
            logger.trace("{} ordered no new requests".format(self))
            return

        if self.instances.masterId is not None:
            self.sendNodeRequestSpike()

            master_throughput, backup_throughput = self.monitor.getThroughputs(0)
            if master_throughput is not None:
                self.metrics.add_event(MetricsName.MONITOR_AVG_THROUGHPUT, master_throughput)
            if backup_throughput is not None:
                self.metrics.add_event(MetricsName.BACKUP_MONITOR_AVG_THROUGHPUT, backup_throughput)

            avg_lat_master, avg_lat_backup = self.monitor.getLatencies()
            if avg_lat_master:
                self.metrics.add_event(MetricsName.MONITOR_AVG_LATENCY, avg_lat_master)

            if avg_lat_backup:
                self.metrics.add_event(MetricsName.BACKUP_MONITOR_AVG_LATENCY, avg_lat_backup)

            degraded_backups = self.monitor.areBackupsDegraded()
            if degraded_backups:
                logger.display('{} backup instances performance degraded'.format(degraded_backups))
                self.backup_instance_faulty_processor.on_backup_degradation(degraded_backups)

            if self.monitor.isMasterDegraded():
                logger.display('{} master instance performance degraded'.format(self))
                self.view_changer.on_master_degradation()
                return False
            else:
                logger.trace("{}'s master has higher performance than backups".
                             format(self))
        return True
171689
public function cpu_usage()
    {
        if ($this->host_os === 'WINDOWS') {
            $wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
            $cpus = $wmi->ExecQuery("SELECT LoadPercentage FROM Win32_Processor");

            foreach ($cpus as $cpu) {
                $return = $cpu->LoadPercentage;
            }
        } else {
            $return = shell_exec('top -d 0.5 -b -n2 | grep "Cpu(s)"|tail -n 1 | awk \'{print $2 + $4}\'');
        }
        return trim($return);
    }
595555
def cpu_frequency(self) -> str:
        
        return '{}GHz'.format(
            self.random.uniform(
                a=1.5,
                b=4.3,
                precision=1,
            ),
        )
248235
def cpu_usage
      result = run("cgroup", "cpuacct.usage").to_s.strip
      result.empty? ? nil : Float("%.4f" % (result.to_i / 1E9))
    end
1166290
@Override
   public double getSortProcessingRate(long currentTime) {
     long timeSpentSorting = 0;
     float progress = 0;
     Phase phase = getPhase();
     long sortFinishTime = getSortFinishTime();
     long shuffleFinishTime = getShuffleFinishTime();
     
     if (phase == Phase.SHUFFLE ) {
       return 0;
     } else if (getPhase() == Phase.SORT) {
       if (shuffleFinishTime < currentTime) {
         LOG.error("Shuffle finish time is " + shuffleFinishTime + 
             " which is < current time " + currentTime + 
             " in " + this.getTaskID());
       }
       timeSpentSorting =  currentTime - shuffleFinishTime;
       progress = getProgress() - (float)1.0/3;
       if (progress < 0) {
         LOG.error("Shuffle progress calculated to be " + progress + 
             " in task status for  " + this.getTaskID() + ".  Settings to 0");
         progress = 0;
       }
     } else if (getPhase() == Phase.REDUCE) {
       // when it is reduce phase, use 33%/(sort finish time - shuffle 
       // finish time as the progress rate. Using percentages instead of bytes
       // as it is tricky
       progress = (float)1.0/3;
       if (shuffleFinishTime <= sortFinishTime) {
         LOG.error("Shuffle finish fime is " + shuffleFinishTime + 
             " which is <= sort finish time " + sortFinishTime + 
             " in " + this.getTaskID());
         return 0;
       }
       timeSpentSorting = sortFinishTime - shuffleFinishTime;
     }
     
     sortProcessingRate = progress/timeSpentSorting; 
     return sortProcessingRate;
   }
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)
19053
def cpu_throttling(self, cpu_throttling):
        

        log.info('QEMU VM "{name}" [{id}] has set the percentage of CPU allowed to {cpu}'.format(name=self._name,
                                                                                                 id=self._id,
                                                                                                 cpu=cpu_throttling))
        self._cpu_throttling = cpu_throttling
        self._stop_cpulimit()
        if cpu_throttling:
            self._set_cpu_throttling()