Get CPU usage in percentage

@return int
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);
    }
414689
public static function getMemoryUsage()
    {
        $memory = false;
        if (function_exists('xdebug_memory_usage')) {
            $memory = xdebug_memory_usage();
        } elseif (function_exists('memory_get_usage')) {
            $memory = memory_get_usage();
        }
        if ($memory === false) {
            return "Memory usage function not found.";
        }
        $usage = number_format(round($memory / 1024 / 1024, 2), 2);
        return "$usage Mb";
    }
317640
public function getServerLoad()
    {
        $load = null;

        if (stristr(PHP_OS, "win")) {
            $cmd = "wmic cpu get loadpercentage /all";
            @exec($cmd, $output);

            if ($output) {
                foreach ($output as $line) {
                    if ($line && preg_match("/^[0-9]+\$/", $line)) {
                        $load = $line;
                        break;
                    }
                }
            }
        } else {
            if (is_readable("/proc/stat"))
            {
                // Collect 2 samples - each with 1 second period
                // See: https://de.wikipedia.org/wiki/Load#Der_Load_Average_auf_Unix-Systemen
                $statData1 = $this->getServerLoadLinuxData();
                sleep(1);
                $statData2 = $this->getServerLoadLinuxData();

                if ((!is_null($statData1)) && (!is_null($statData2))) {
                    // Get difference
                    $statData2[0] -= $statData1[0];
                    $statData2[1] -= $statData1[1];
                    $statData2[2] -= $statData1[2];
                    $statData2[3] -= $statData1[3];

                    // Sum up the 4 values for User, Nice, System and Idle and calculate
                    // the percentage of idle time (which is part of the 4 values!)
                    $cpuTime = $statData2[0] + $statData2[1] + $statData2[2] + $statData2[3];

                    // Invert percentage to get CPU time, not idle time
                    $load = 100 - ($statData2[3] * 100 / $cpuTime);
                }
            }
        }

        return $load;
    }
444243
public function getOutput()
    {
        $totalExecution = profiler()->getTotalExecution();
        $metrics = profiler()->getMetrics();

        $totalTime = 0;
        $totalMemory = 0;

        foreach ($metrics as $metric) {
            $totalTime += ($metric->endTime - $metric->startTime);
            $totalMemory += ($metric->endMemory - $metric->startMemory);
        }

        $segmentDuration = $this->roundTo($totalTime * 1000, 5);
        $segmentCount = (int)ceil($totalTime / $segmentDuration);

        $displayTime = $segmentCount * $segmentDuration;

        foreach ($metrics as $metric) {
            $metric->offset = (($metric->startTime - $totalExecution->startTime) * 1000 / $displayTime) * 100;
            $metric->length = (($metric->endTime - $metric->startTime) * 1000 / $displayTime) * 100;
        }

        $totalTime = $totalExecution->getFormattedTime($totalTime, 2);
        $totalMemory = $totalExecution->getFormattedMemorySize($totalMemory);
        $allocatedMemory = $totalExecution->getFormattedMemorySize(memory_get_usage(true));
        $peakMemory = $totalExecution->getFormattedMemorySize(memory_get_peak_usage(true));

        $files = $this->getFiles();
        $logs = $this->getLogs();
        $vars = $this->getVars();
        $database = $this->getDatabase();

        ob_start();
        include __DIR__ . '/Views/Toolbar.php';
        $output = ob_get_contents();
        ob_end_clean();

        return $output;
    }
512468
public function throttle()
    {
        if ((time() - $this->lastCpuCheck) >= $this->cpuCheckFrequency) {
            $load = sys_getloadavg();
            
            if ($load[0]/$this->cpuCount >= $this->cpuTarget) {
                $this->pause += $this->throttleSensitivity;
                $this->controller->notify('Daemon throttling down');
            } else {
                $this->pause -= $this->throttleSensitivity;
                $this->controller->notify('Daemon throttling up');
            }

            $this->lastCpuCheck = time();
        }

        // Never allow pause to dip below 1 microsecond
        if ($this->pause < 1) {
            $this->pause = 1;
        }

        return $this->pause;
    }
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;
	}
1196560
public function getFillingPercentage()
    {
        $free = disk_free_space($this->_options['cache_dir']);
        $total = disk_total_space($this->_options['cache_dir']);
        if ($total == 0) {
            Zend_Cache::throwException('can\'t get disk_total_space');
        } else {
            if ($free >= $total) {
                return 100;
            }
            return ((int) (100. * ($total - $free) / $total));
        }
    }
1069130
public function returnFullDataSystem() {

        $aStorage = $this->getSNMP()->realWalk1d(self::OID_SYSTEM);

        $aReturn = Array();
        $aReturn['uptime'] = $aStorage[self::OID_SYSTEM_UPTIME][0] / 100;
        $aReturn['num_users'] = $aStorage[self::OID_SYSTEM_NUM_USERS][0];
        $aReturn['processes'] = $aStorage[self::OID_SYSTEM_PROCESSES][0];
        $aReturn['max_processes'] = $aStorage[self::OID_SYSTEM_MAX_PROCESSES][0];

        return $aReturn;
    }
67797
def calculate_usage(self, cpu, total, busy):
        
        diff_total = total - self.prev_total[cpu]
        diff_busy = busy - self.prev_busy[cpu]

        self.prev_total[cpu] = total
        self.prev_busy[cpu] = busy

        if diff_total == 0:
            return 0
        else:
            return int(diff_busy / diff_total * 100)
85857
protected function _cpuinfo()
    {
        if (CommonFunctions::executeProgram('pidin', 'info', $buf)
           && preg_match('/^Processor\d+: (.*)/m', $buf)) {
            $lines = preg_split("/\n/", $buf, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($lines as $line) {
                if (preg_match('/^Processor\d+: (.+)/', $line, $proc)) {
                    $dev = new CpuDevice();
                    $dev->SetModel(trim($proc[1]));
                    if (preg_match('/(\d+)MHz/', $proc[1], $mhz)) {
                        $dev->setCpuSpeed($mhz[1]);
                    }
                    $this->sys->setCpus($dev);
                }
            }
        }
    }
351481
public function memory_total()
    {
        $mem_total = 0;
        if ($this->host_os === 'WINDOWS') {
            $wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
            $os =  $wmi->ExecQuery("SELECT * FROM Win32_OperatingSystem");

            foreach ($os as $m) {
                $mem_total = $m->TotalVisibleMemorySize;
            }
        } else {
            $fh = fopen('/proc/meminfo', 'r');

            while ($line = fgets($fh)) {
                $pieces = array();
                if (preg_match('/^MemTotal:\s+(\d+)\skB$/', trim($line), $pieces)) {
                    $mem_total = $pieces[1];
                    break;
                }
            }
            fclose($fh);
        }
        return $mem_total;
    }
470072
public function getProcessStats()
    {

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

        // We'll return this after stuffing it with useful info
        $result = array(
            'exists' => true,
            'totals' => array(
                'running' => 0,
                'zombie' => 0,
                'sleeping' => 0,
                'stopped' => 0,
            ),
            'proc_total' => 0,
            'threads' => 0,
        );

        // Get all the paths to each process' status file
        $processes = (array) @glob('/proc/*/status', GLOB_NOSORT);

        // Total
        $result['proc_total'] = count($processes);

        // Go through each
        foreach ($processes as $process) {

            // Don't waste time if we can't use it
            if (!is_readable($process)) {
                continue;
            }

            // Get that file's contents
            $status_contents = Common::getContents($process);

            // Try getting state
            @preg_match('/^State:\s+(\w)/m', $status_contents, $state_match);

            // Well? Determine state
            switch ($state_match[1]) {
                case 'D': // disk sleep? wtf?
                case 'S':
                    $result['totals']['sleeping']++;
                break;
                case 'Z':
                    $result['totals']['zombie']++;
                break;
                case 'R':
                    $result['totals']['running']++;
                break;
                case 'T':
                    $result['totals']['stopped']++;
                break;
            }

            // Try getting number of threads
            @preg_match('/^Threads:\s+(\d+)/m', $status_contents, $threads_match);

            // Well?
            if ($threads_match) {
                list(, $threads) = $threads_match;
            }

            // Append it on if it's good
            if (is_numeric($threads)) {
                $result['threads'] = $result['threads'] + $threads;
            }
        }

        // Give off result
        return $result;
    }
709848
public function getMostUsedVatPercent()
    {
        $aPrices = $this->getPriceInfo();
        if (count($aPrices) == 0) {
            return;
        }

        return max(array_keys($aPrices, max($aPrices)));
    }
1170478
protected function cpuinfo()
    {
        $dev = new CpuDevice();
        if (CommonFunctions::executeProgram('hostinfo', '| grep "Processor type"', $buf, PSI_DEBUG)) {
            $dev->setModel(preg_replace('/Processor type: /', '', $buf));
            $buf=$this->grabkey('hw.model');
            if (!is_null($buf) && (trim($buf) != "")) {
                $this->sys->setMachine(trim($buf));
                if (CommonFunctions::rfts(PSI_APP_ROOT.'/data/ModelTranslation.txt', $buffer)) {
                    $buffer = preg_split("/\n/", $buffer, -1, PREG_SPLIT_NO_EMPTY);
                    foreach ($buffer as $line) {
                        $ar_buf = preg_split("/:/", $line, 3);
                        if (trim($buf) === trim($ar_buf[0])) {
                            $dev->setModel(trim($ar_buf[2]));
                            $this->sys->setMachine($this->sys->getMachine().' - '.trim($ar_buf[1]));
                            break;
                        }
                    }
                }
            }
            $buf=$this->grabkey('machdep.cpu.brand_string');
            if (!is_null($buf) && (trim($buf) != "") &&
                 ((trim($buf) != "i486 (Intel 80486)") || ($dev->getModel() == ""))) {
                $dev->setModel(trim($buf));
            }
            $buf=$this->grabkey('machdep.cpu.features');
            if (!is_null($buf) && (trim($buf) != "")) {
                if (preg_match("/ VMX/", $buf)) {
                    $dev->setVirt("vmx");
                } elseif (preg_match("/ SVM/", $buf)) {
                    $dev->setVirt("svm");
                }
            }
        }
        $dev->setCpuSpeed(round($this->grabkey('hw.cpufrequency') / 1000000));
        $dev->setBusSpeed(round($this->grabkey('hw.busfrequency') / 1000000));
        $bufn=$this->grabkey('hw.cpufrequency_min');
        $bufx=$this->grabkey('hw.cpufrequency_max');
        if (!is_null($bufn) && (trim($bufn) != "") && !is_null($bufx) && (trim($bufx) != "") && ($bufn != $bufx)) {
            $dev->setCpuSpeedMin(round($bufn / 1000000));
            $dev->setCpuSpeedMax(round($bufx / 1000000));
        }
        $buf=$this->grabkey('hw.l2cachesize');
        if (!is_null($buf) && (trim($buf) != "")) {
            $dev->setCache(round($buf));
        }
        $ncpu = $this->grabkey('hw.ncpu');
        if (is_null($ncpu) || (trim($ncpu) == "") || (!($ncpu >= 1)))
            $ncpu = 1;
        for ($ncpu ; $ncpu > 0 ; $ncpu--) {
            $this->sys->setCpus($dev);
        }
    }
839696
public function getMemPercentCache()
    {
        if ($this->_memCache !== null) {
            if (($this->_memCache > 0) && ($this->_memTotal > 0)) {
                if (($this->_memApplication !== null) && ($this->_memApplication > 0)) {
                    return round(($this->_memCache + $this->_memApplication) / $this->_memTotal * 100) - $this->getMemPercentApplication();
                } else {
                    return round($this->_memCache / $this->_memTotal * 100);
                }
            } else {
                return 0;
            }
        } else {
            return null;
        }
    }
614431
public function getUsage()
    {
        if ($this->usage === null) {
            $calculator = new SizeCalculator();
            $calculatedSize = $calculator->calculate($this->volume, $this->volume->findRootFolder());

            $this->usage = $calculatedSize->getSize();
        }

        return $this->usage;
    }
1148204
public function remainingCoolDown() : int
    {
        $now = time();

        if ($this->cache->has($this->cacheKey)) {
            $executedAt = $this->cache->get($this->cacheKey);

            $remainingCoolDown = $executedAt + $this->coolDown * 60 - $now;

            return max($remainingCoolDown / 60, 0);
        }

        return 0;
    }