Returns the system CPU usage, in percents, between 0 and 100.

@return total CPU usage of the current OS
771246
@Override
	protected long detectPID() throws Exception {
		String jvmName = ManagementFactory.getRuntimeMXBean().getName();
		int index = jvmName.indexOf('@');
		if (index < 1) {
			return 0;
		}
		return Long.parseLong(jvmName.substring(0, index));
	}
1211998
private Double getSystemCpuLoad() {
        if (bean instanceof com.sun.management.OperatingSystemMXBean) { //NOSONAR
            return ((com.sun.management.OperatingSystemMXBean) bean).getSystemCpuLoad() * 100.0;  //NOSONAR
        } else {
            return -1.0;
        }
    }
570055
def cpu
      cpus = []
      procfs_file("stat") do |file|
        file.read.scan(CPU_DATA) do |i, user, nice, system, idle|
          cpus << Cpu.new(i.to_i, user.to_i, system.to_i, nice.to_i, idle.to_i)
        end
      end
      cpus
    end
659951
public function getVersion()
    {
        $cpuinfo = preg_split("/\n/", file_get_contents('/proc/cpuinfo'));
        foreach ($cpuinfo as $line) {
            if (preg_match('/Revision\s*:\s*([^\s]*)\s*/', $line, $matches)) {
                return hexdec($matches[1]);
            }
        }

        return 0;
    }
974935
def get_usage(self):
        
        usage = {}

        for cpu, timings in self.get_cpu_timings().items():
            cpu_total = sum(timings)
            del timings[3:5]
            cpu_busy = sum(timings)
            cpu_usage = self.calculate_usage(cpu, cpu_total, cpu_busy)

            usage['usage_' + cpu] = cpu_usage

        # for backward compatibility
        usage['usage'] = usage['usage_cpu']

        return usage
909715
public static OperatingSystemType getOs() {
        OperatingSystemType os = OperatingSystemType.UNKNOWN;

        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            if (System.getenv("ProgramFiles(x86)") != null) {
                // win 64Bit
                os = OperatingSystemType.WIN64;
            } else if (System.getenv("ProgramFiles") != null) {
                // win 32Bit
                os = OperatingSystemType.WIN32;
            }

        } else if (SystemInfo.isLinux()) {
            os = OperatingSystemType.LINUX;
        } else if (System.getProperty("os.name").toLowerCase().contains("freebsd")) {
            os = OperatingSystemType.LINUX;

        } else if (SystemInfo.isMacOSX()) {
            os = OperatingSystemType.MAC;
        }
        return os;
    }
792944
public static systemmemory_stats get(nitro_service service) throws Exception{
		systemmemory_stats obj = new systemmemory_stats();
		systemmemory_stats[] response = (systemmemory_stats[])obj.stat_resources(service);
		return response[0];
	}
391010
public function getCPU()
    {

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

        $cpus = array();
        $alt = false;
        $object = $this->wmi->ExecQuery('SELECT Name, Manufacturer, CurrentClockSpeed, NumberOfLogicalProcessors,LoadPercentage FROM Win32_Processor');

        if (!is_object($object)) {
            $object = $this->wmi->ExecQuery('SELECT Name, Manufacturer, CurrentClockSpeed,LoadPercentage FROM Win32_Processor');
            $alt = true;
        }

        foreach ($object as $cpu) {
            $curr = array(
                'Model' => $cpu->Name,
                'Vendor' => $cpu->Manufacturer,
                'MHz' => $cpu->CurrentClockSpeed,
            );

            if ($cpu->LoadPercentage != '') {
                $curr['usage_percentage'] = $cpu->LoadPercentage;
            }

            if (!$alt) {
                for ($i = 0; $i < $cpu->NumberOfLogicalProcessors; ++$i) {
                    $cpus[] = $curr;
                }
            } else {
                $cpus[] = $curr;
            }
        }

        return $cpus;
    }
892414
function getLoad() {

  return new Promise((resolve) => {
    process.nextTick(() => {
      let loads = os.loadavg().map(function (x) { return x / util.cores(); });
      let avgload = parseFloat((Math.max.apply(Math, loads)).toFixed(2));
      let result = {};

      let now = Date.now() - _current_cpu.ms;
      if (now >= 200) {
        _current_cpu.ms = Date.now();
        const cpus = os.cpus();
        let totalUser = 0;
        let totalSystem = 0;
        let totalNice = 0;
        let totalIrq = 0;
        let totalIdle = 0;
        let cores = [];
        _corecount = cpus.length;

        for (let i = 0; i < _corecount; i++) {
          const cpu = cpus[i].times;
          totalUser += cpu.user;
          totalSystem += cpu.sys;
          totalNice += cpu.nice;
          totalIdle += cpu.idle;
          totalIrq += cpu.irq;
          let tmp_tick = (_cpus && _cpus[i] && _cpus[i].totalTick ? _cpus[i].totalTick : 0);
          let tmp_load = (_cpus && _cpus[i] && _cpus[i].totalLoad ? _cpus[i].totalLoad : 0);
          let tmp_user = (_cpus && _cpus[i] && _cpus[i].user ? _cpus[i].user : 0);
          let tmp_system = (_cpus && _cpus[i] && _cpus[i].sys ? _cpus[i].sys : 0);
          let tmp_nice = (_cpus && _cpus[i] && _cpus[i].nice ? _cpus[i].nice : 0);
          let tmp_idle = (_cpus && _cpus[i] && _cpus[i].idle ? _cpus[i].idle : 0);
          let tmp_irq = (_cpus && _cpus[i] && _cpus[i].irq ? _cpus[i].irq : 0);
          _cpus[i] = cpu;
          _cpus[i].totalTick = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].idle;
          _cpus[i].totalLoad = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq;
          _cpus[i].currentTick = _cpus[i].totalTick - tmp_tick;
          _cpus[i].load = (_cpus[i].totalLoad - tmp_load);
          _cpus[i].load_user = (_cpus[i].user - tmp_user);
          _cpus[i].load_system = (_cpus[i].sys - tmp_system);
          _cpus[i].load_nice = (_cpus[i].nice - tmp_nice);
          _cpus[i].load_idle = (_cpus[i].idle - tmp_idle);
          _cpus[i].load_irq = (_cpus[i].irq - tmp_irq);
          cores[i] = {};
          cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
          cores[i].load_user = _cpus[i].load_user / _cpus[i].currentTick * 100;
          cores[i].load_system = _cpus[i].load_system / _cpus[i].currentTick * 100;
          cores[i].load_nice = _cpus[i].load_nice / _cpus[i].currentTick * 100;
          cores[i].load_idle = _cpus[i].load_idle / _cpus[i].currentTick * 100;
          cores[i].load_irq = _cpus[i].load_irq / _cpus[i].currentTick * 100;
          cores[i].raw_load = _cpus[i].load;
          cores[i].raw_load_user = _cpus[i].load_user;
          cores[i].raw_load_system = _cpus[i].load_system;
          cores[i].raw_load_nice = _cpus[i].load_nice;
          cores[i].raw_load_idle = _cpus[i].load_idle;
          cores[i].raw_load_irq = _cpus[i].load_irq;
        }
        let totalTick = totalUser + totalSystem + totalNice + totalIrq + totalIdle;
        let totalLoad = totalUser + totalSystem + totalNice + totalIrq;
        let currentTick = totalTick - _current_cpu.tick;
        result = {
          avgload: avgload,
          currentload: (totalLoad - _current_cpu.load) / currentTick * 100,
          currentload_user: (totalUser - _current_cpu.user) / currentTick * 100,
          currentload_system: (totalSystem - _current_cpu.system) / currentTick * 100,
          currentload_nice: (totalNice - _current_cpu.nice) / currentTick * 100,
          currentload_idle: (totalIdle - _current_cpu.idle) / currentTick * 100,
          currentload_irq: (totalIrq - _current_cpu.irq) / currentTick * 100,
          raw_currentload: (totalLoad - _current_cpu.load),
          raw_currentload_user: (totalUser - _current_cpu.user),
          raw_currentload_system: (totalSystem - _current_cpu.system),
          raw_currentload_nice: (totalNice - _current_cpu.nice),
          raw_currentload_idle: (totalIdle - _current_cpu.idle),
          raw_currentload_irq: (totalIrq - _current_cpu.irq),
          cpus: cores
        };
        _current_cpu = {
          user: totalUser,
          nice: totalNice,
          system: totalSystem,
          idle: totalIdle,
          irq: totalIrq,
          tick: totalTick,
          load: totalLoad,
          ms: _current_cpu.ms,
          currentload: result.currentload,
          currentload_user: result.currentload_user,
          currentload_system: result.currentload_system,
          currentload_nice: result.currentload_nice,
          currentload_idle: result.currentload_idle,
          currentload_irq: result.currentload_irq,
          raw_currentload: result.raw_currentload,
          raw_currentload_user: result.raw_currentload_user,
          raw_currentload_system: result.raw_currentload_system,
          raw_currentload_nice: result.raw_currentload_nice,
          raw_currentload_idle: result.raw_currentload_idle,
          raw_currentload_irq: result.raw_currentload_irq,
        };
      } else {
        let cores = [];
        for (let i = 0; i < _corecount; i++) {
          cores[i] = {};
          cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
          cores[i].load_user = _cpus[i].load_user / _cpus[i].currentTick * 100;
          cores[i].load_system = _cpus[i].load_system / _cpus[i].currentTick * 100;
          cores[i].load_nice = _cpus[i].load_nice / _cpus[i].currentTick * 100;
          cores[i].load_idle = _cpus[i].load_idle / _cpus[i].currentTick * 100;
          cores[i].load_irq = _cpus[i].load_irq / _cpus[i].currentTick * 100;
          cores[i].raw_load = _cpus[i].load;
          cores[i].raw_load_user = _cpus[i].load_user;
          cores[i].raw_load_system = _cpus[i].load_system;
          cores[i].raw_load_nice = _cpus[i].load_nice;
          cores[i].raw_load_idle = _cpus[i].load_idle;
          cores[i].raw_load_irq = _cpus[i].load_irq;
        }
        result = {
          avgload: avgload,
          currentload: _current_cpu.currentload,
          currentload_user: _current_cpu.currentload_user,
          currentload_system: _current_cpu.currentload_system,
          currentload_nice: _current_cpu.currentload_nice,
          currentload_idle: _current_cpu.currentload_idle,
          currentload_irq: _current_cpu.currentload_irq,
          raw_currentload: _current_cpu.raw_currentload,
          raw_currentload_user: _current_cpu.raw_currentload_user,
          raw_currentload_system: _current_cpu.raw_currentload_system,
          raw_currentload_nice: _current_cpu.raw_currentload_nice,
          raw_currentload_idle: _current_cpu.raw_currentload_idle,
          raw_currentload_irq: _current_cpu.raw_currentload_irq,
          cpus: cores
        };
      }
      resolve(result);
    });
  });
}
634609
def __get_cpu(self):
        """"""
        # Never update more than 1 time per cached_time
        if self.timer_cpu.finished():
            self.cpu_percent = psutil.cpu_percent(interval=0.0)
            # Reset timer for cache
            self.timer_cpu = Timer(self.cached_time)
        return self.cpu_percent
445963
def get_environment(self):
        

        environment = {}
        # sys_resources contains cpu and mem output
        sys_resources = self._send_command("show system resources")
        temp_cmd = "show environment temperature"

        # cpu
        environment.setdefault("cpu", {})
        environment["cpu"]["0"] = {}
        environment["cpu"]["0"]["%usage"] = -1.0
        system_resources_cpu = helpers.textfsm_extractor(
            self, "system_resources", sys_resources
        )
        for cpu in system_resources_cpu:
            cpu_dict = {
                cpu.get("cpu_id"): {
                    "%usage": round(100 - float(cpu.get("cpu_idle")), 2)
                }
            }
            environment["cpu"].update(cpu_dict)

        # memory
        environment.setdefault("memory", {})
        for line in sys_resources.splitlines():
            # Memory usage:   16401224K total,   4798280K used,   11602944K free
            if "Memory usage:" in line:
                proc_total_mem, proc_used_mem, _ = line.split(",")
                proc_used_mem = re.search(r"\d+", proc_used_mem).group(0)
                proc_total_mem = re.search(r"\d+", proc_total_mem).group(0)
                break
        else:
            raise ValueError("Unexpected output from: {}".format(line))
        environment["memory"]["used_ram"] = int(proc_used_mem)
        environment["memory"]["available_ram"] = int(proc_total_mem)

        # temperature
        output = self._send_command(temp_cmd)
        environment.setdefault("temperature", {})
        for line in output.splitlines():
            # Module   Sensor        MajorThresh   MinorThres   CurTemp     Status
            # 1        Intake          70              42          28         Ok
            if re.match(r"^[0-9]", line):
                module, sensor, is_critical, is_alert, temp, _ = line.split()
                is_critical = float(is_critical)
                is_alert = float(is_alert)
                temp = float(temp)
                env_value = {
                    "is_alert": temp >= is_alert,
                    "is_critical": temp >= is_critical,
                    "temperature": temp,
                }
                location = "{0}-{1}".format(sensor, module)
                environment["temperature"][location] = env_value

        # Initialize 'power' and 'fan' to default values (not implemented)
        environment.setdefault("power", {})
        environment["power"]["invalid"] = {
            "status": True,
            "output": -1.0,
            "capacity": -1.0,
        }
        environment.setdefault("fans", {})
        environment["fans"]["invalid"] = {"status": True}

        return environment
255447
public static OS getOS() {
        String osname = SystemUtil.OS_NAME;
        String osarch = SystemUtil.OS_ARCH;

        if (osname.indexOf("Mac") != -1) {
            if (osarch.equals("x86")) return OS.MAC;
            else if (osarch.equals("x86_64")) return OS.MAC_64;
        } else if (osname.indexOf("Windows") != -1) {
            if (osarch.equals("x86")) return OS.WIN;
            else if (osarch.equals("x86_64")||osarch.equals("amd64")) return OS.WIN_64;
        } else if (osname.indexOf("Linux") != -1) {
            if (osarch.equals("i386")) return OS.LINUX;
            else if (osarch.equals("amd64")) return OS.LINUX_64;
        }

        return OS.OTHER;
    }
768368
def ncores_used(self):
        
        return sum(task.manager.num_cores for task in self if task.status == task.S_RUN)
30620
public function determineCPUPercentage()
     {
         // Time?
         if (!empty($this->settings['timer'])) {
             $t = new Timer('Determining CPU usage');
         }

         $iterations = 2;

         // Probably only inline function here. Only used once so it makes sense.

         for ($i = 0; $i < $iterations; ++$i) {
             $contents = Common::getContents('/proc/stat', false);

             // Yay we can't read it so we won't sleep below!
             if (!$contents) {
                 continue;
             }

             // Overall system CPU usage
             if (preg_match('/^cpu\s+(.+)/', $contents, $m)) {
                 $this->cpu_percent['overall'] = $this->cpuPercent('overall', $m[1]);
             }

             // CPU usage per CPU
             if (preg_match_all('/^cpu(\d+)\s+(.+)/m', $contents, $cpus, PREG_SET_ORDER)) {
                 foreach ($cpus as $cpu) {
                     $this->cpu_percent['cpus'][$cpu[1]] = $this->cpuPercent('c'.$cpu[1], $cpu[2]);
                 }
             }

             // Following two lines make me want to puke as they go against everything linfo stands for
             // this functionality will always be disabled by default
             // Sleep *between* iterations and only if we're doing at least two of them
             if ($iterations > 1 && $i != $iterations - 1) {
                 sleep(1);
             }
         }
     }
366402
public float getCpuUsagePercent() {
		if (nanoBefore == null || cpuBefore == null) {
			throw new IllegalStateException("nanoBefore or cpuBefore where null: nanoBefore: " + nanoBefore + ", " +
					" cpuBefore: " + cpuBefore);
		}
		long cpuAfter = processCpuTime.getProcessCpuTime();
		long nanoAfter = System.nanoTime();

		float utilisation = ((float)(cpuAfter - cpuBefore)) / (nanoAfter - nanoBefore);
		return utilisation / Runtime.getRuntime().availableProcessors();
	}
268733
public T getTotal() {
        Lock lock = this.lock.readLock();
        lock.lock();
        try {
            return this.total;
        } finally {
            lock.unlock();
        }
    }
339960
public Map<String, Object> getThreadCpuUsages(CpuUsageComparator cmp) {
    final CpuUsage overall = getOverallCpuUsage();
    final List<CpuUsage> usages = getThreadCpuUsages();
    final Map<String, Object> result = new HashMap<>();

    Collections.sort(usages, cmp);

    final Date now = new Date();
    result.put(CURRENT_TIME, now.getTime());

    final long uptimeMillis = ManagementFactory.getRuntimeMXBean().getUptime();
    final long uptimeNanos = TimeUnit.NANOSECONDS.convert(uptimeMillis, TimeUnit.MILLISECONDS);
    result.put(UPTIME_MS, uptimeMillis);

    final Map<String, Long> jvmUsageTime = new HashMap<>();
    jvmUsageTime.put(ONE_MIN, overall.getOneMinute());
    jvmUsageTime.put(FIVE_MIN, overall.getFiveMinute());
    jvmUsageTime.put(FIFTEEN_MIN, overall.getFifteenMinute());
    jvmUsageTime.put(OVERALL, overall.getOverall());
    result.put(JVM_USAGE_TIME, jvmUsageTime);

    final Map<String, Double> jvmUsagePercent = new HashMap<>();
    final int numProcs = Runtime.getRuntime().availableProcessors();
    jvmUsagePercent.put(ONE_MIN, toPercent(overall.getOneMinute(),
        ONE_MINUTE_NANOS * numProcs));
    jvmUsagePercent.put(FIVE_MIN, toPercent(overall.getFiveMinute(),
        FIVE_MINUTE_NANOS * numProcs));
    jvmUsagePercent.put(FIFTEEN_MIN, toPercent(overall.getFifteenMinute(),
        FIFTEEN_MINUTE_NANOS * numProcs));
    jvmUsagePercent.put(OVERALL, toPercent(overall.getOverall(), uptimeNanos * numProcs));
    result.put(JVM_USAGE_PERCENT, jvmUsagePercent);

    List<Map<String, Object>> threads = new ArrayList<>();
    for (CpuUsage usage : usages) {
      Map<String, Object> threadInfo = new HashMap<>();
      threadInfo.put(ONE_MIN, toPercent(usage.getOneMinute(), overall.getOneMinute()));
      threadInfo.put(FIVE_MIN, toPercent(usage.getFiveMinute(), overall.getFiveMinute()));
      threadInfo.put(FIFTEEN_MIN, toPercent(usage.getFifteenMinute(),
          overall.getFifteenMinute()));
      threadInfo.put(OVERALL, toPercent(usage.getOverall(), overall.getOverall()));
      threadInfo.put(ID, usage.getThreadId());
      threadInfo.put(NAME, usage.getName());
      threads.add(threadInfo);
    }
    result.put(THREADS, threads);
    return result;
  }