Shows cpu usage in seconds, "cpu_id" is ignored.

        :returns: cpu usage in seconds
336566
def get_cpu_usage(self, cpu_id=0):
        

        cpu_usage = yield from self._hypervisor.send('vm cpu_usage "{name}" {cpu_id}'.format(name=self._name, cpu_id=cpu_id))
        return int(cpu_usage[0])
107617
def _get_cpu_info_from_dmesg():
	'''
	
	'''
	# Just return {} if there is no dmesg
	if not DataSource.has_dmesg():
		return {}

	# If dmesg fails return {}
	returncode, output = DataSource.dmesg_a()
	if output == None or returncode != 0:
		return {}

	return _parse_dmesg_output(output)
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);
    }
797416
def idle_task(self):
        ''''''
        if not self.started:
            return
        now = time.time()
        if now - self.last_packet < 1:
            timeout = 0.05
        else:
            timeout = 0.2
        if now - self.last_check > timeout:
            self.last_check = now
            mav = self.master.mav
            flags = mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND
            flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_MULTI
            flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE
            mav.serial_control_send(self.serial_settings.port,
                                    flags,
                                    0, self.serial_settings.baudrate,
                                    0, [0]*70)
1329400
def usage(interval = 1, &block)
      unless @usage
        if processor = CPU.usage(interval, &block).find {
          |p| p.processor_id == processor_id
        }
        then
          @usage = processor.usage
        end
      end
      @usage
    end
169518
function() {
        if (process.platform !== 'win32') {
            return;
        }

        this._cpuConsole = child_process.spawn('typeperf', ['\\Processor(_Total)\\% Processor Time']);
        this._cpuConsole.stdout.on('data', _.bind(function(stdout) {

            stdout = stdout.toString();
            if (stdout && stdout.indexOf(',') === 0) {
                var cpu = parseFloat(stdout.substr(2, stdout.length - 3));
                this._cpuFrame(cpu);
            }
        }, this));
    }
1096546
def _get_cpu_info_from_cpuid():
	'''
	
	'''
	from multiprocessing import Process, Queue

	# Return {} if can't cpuid
	if not DataSource.can_cpuid:
		return {}

	# Get the CPU arch and bits
	arch, bits = _parse_arch(DataSource.arch_string_raw)

	# Return {} if this is not an X86 CPU
	if not arch in ['X86_32', 'X86_64']:
		return {}

	try:
		# Start running the function in a subprocess
		queue = Queue()
		p = Process(target=_actual_get_cpu_info_from_cpuid, args=(queue,))
		p.start()

		# Wait for the process to end, while it is still alive
		while p.is_alive():
			p.join(0)

		# Return {} if it failed
		if p.exitcode != 0:
			return {}

		# Return the result, only if there is something to read
		if not queue.empty():
			output = queue.get()
			return _b64_to_obj(output)
	except:
		pass

	# Return {} if everything failed
	return {}
1089959
def _perform_system_check(self):
        
        if Global.CONFIG_MANAGER.tracing_mode:
            Global.LOGGER.debug("performing a system check")

        now = datetime.datetime.now()
        sent = Global.MESSAGE_DISPATCHER.dispatched
        received = self.fetched
        queue_length = sent - received
        message_sleep_interval = Global.CONFIG_MANAGER.message_fetcher_sleep_interval

        if Global.CONFIG_MANAGER.show_stats:
            if (now - self.last_stats_check_date).total_seconds() > Global.CONFIG_MANAGER.stats_timeout:
                self.last_stats_check_date = now
                stats_string = f"showing stats\n--- [STATS] ---\nMessage Sent: {sent}\nMessage Received: {received}\nMessage Sleep Interval = {message_sleep_interval}\nQueue length = {queue_length}\n--- [ END ] ---"
                Global.LOGGER.info(stats_string)

        # if we are accumulating messages, or we have processed at least 5000 messages
        # since last check, we need to speed up the process
        messages_limit_reached = sent - self.last_queue_check_count > Global.CONFIG_MANAGER.messages_dispatched_for_system_check
        queue_limit_reached = queue_length > Global.CONFIG_MANAGER.queue_length_for_system_check
        time_limit_since_last_check_is_over = (now - self.last_queue_check_date).total_seconds() > Global.CONFIG_MANAGER.seconds_between_queue_check

        if not Global.CONFIG_MANAGER.fixed_message_fetcher_interval:
            if (messages_limit_reached) or (queue_limit_reached and time_limit_since_last_check_is_over):
                cause = "messages limit reached" if messages_limit_reached else "queue limit reached"
                Global.LOGGER.debug(f"triggering the throttle function due to {cause}")
                self._adapt_sleep_interval(sent, received, queue_length, now)
1120741
def get_environment(self):
        
        environment = {}
        cpu_cmd = "show proc cpu"
        mem_cmd = "show memory statistics"
        temp_cmd = "show env temperature status"

        output = self._send_command(cpu_cmd)
        environment.setdefault("cpu", {})
        environment["cpu"][0] = {}
        environment["cpu"][0]["%usage"] = 0.0
        for line in output.splitlines():
            if "CPU utilization" in line:
                # CPU utilization for five seconds: 2%/0%; one minute: 2%; five minutes: 1%
                cpu_regex = r"^.*one minute: (\d+)%; five.*$"
                match = re.search(cpu_regex, line)
                environment["cpu"][0]["%usage"] = float(match.group(1))
                break

        output = self._send_command(mem_cmd)
        for line in output.splitlines():
            if "Processor" in line:
                _, _, proc_total_mem, proc_used_mem, _ = line.split()[:5]
            elif "I/O" in line or "io" in line:
                _, _, io_total_mem, io_used_mem, _ = line.split()[:5]
        total_mem = int(proc_total_mem) + int(io_total_mem)
        used_mem = int(proc_used_mem) + int(io_used_mem)
        environment.setdefault("memory", {})
        environment["memory"]["used_ram"] = used_mem
        environment["memory"]["available_ram"] = total_mem

        environment.setdefault("temperature", {})
        re_temp_value = re.compile("(.*) Temperature Value")
        # The 'show env temperature status' is not ubiquitous in Cisco IOS
        output = self._send_command(temp_cmd)
        if "% Invalid" not in output:
            for line in output.splitlines():
                m = re_temp_value.match(line)
                if m is not None:
                    temp_name = m.group(1).lower()
                    temp_value = float(line.split(":")[1].split()[0])
                    env_value = {
                        "is_alert": False,
                        "is_critical": False,
                        "temperature": temp_value,
                    }
                    environment["temperature"][temp_name] = env_value
                elif "Yellow Threshold" in line:
                    system_temp_alert = float(line.split(":")[1].split()[0])
                    if temp_value > system_temp_alert:
                        env_value["is_alert"] = True
                elif "Red Threshold" in line:
                    system_temp_crit = float(line.split(":")[1].split()[0])
                    if temp_value > system_temp_crit:
                        env_value["is_critical"] = True
        else:
            env_value = {"is_alert": False, "is_critical": False, "temperature": -1.0}
            environment["temperature"]["invalid"] = 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
565343
def cpu_count(logical=True):
    
    if logical:
        from multiprocessing import cpu_count
        ncpu=cpu_count()
    else:
        import psutil
        ncpu=psutil.cpu_count(logical=False)
    return ncpu
540283
def cpu_count() -> int:
    """"""
    if multiprocessing is None:
        return 1
    try:
        return multiprocessing.cpu_count()
    except NotImplementedError:
        pass
    try:
        return os.sysconf("SC_NPROCESSORS_CONF")
    except (AttributeError, ValueError):
        pass
    gen_log.error("Could not detect number of processors; assuming 1")
    return 1
283358
def get_num_processes():
    """"""
    cpu_count = multiprocessing.cpu_count()

    if config.NUMBER_OF_CORES == 0:
        raise ValueError(
            'Invalid NUMBER_OF_CORES; value may not be 0.')

    if config.NUMBER_OF_CORES > cpu_count:
        log.info('Requesting %s cores; only %s available',
                 config.NUMBER_OF_CORES, cpu_count)
        return cpu_count

    if config.NUMBER_OF_CORES < 0:
        num = cpu_count + config.NUMBER_OF_CORES + 1
        if num <= 0:
            raise ValueError(
                'Invalid NUMBER_OF_CORES; negative value is too negative: '
                'requesting {} cores, {} available.'.format(num, cpu_count))

        return num

    return config.NUMBER_OF_CORES
390370
def is_idle(self):
        
        return (self.status is None or
                self.app_id in (None, IDLE_APP_ID) or
                (not self.status.is_active_input and not self.ignore_cec))
1230668
def _is_second_run():
    """"""
    tracker_path = _get_not_configured_usage_tracker_path()
    if not tracker_path.exists():
        return False

    current_pid = _get_shell_pid()
    with tracker_path.open('r') as tracker:
        try:
            info = json.load(tracker)
        except ValueError:
            return False

    if not (isinstance(info, dict) and info.get('pid') == current_pid):
        return False

    return (_get_previous_command() == 'fuck' or
            time.time() - info.get('time', 0) < const.CONFIGURATION_TIMEOUT)
404225
def available_cpu_count() -> int:
    

    # cpuset
    # cpuset may restrict the number of *available* processors
    try:
        match = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
                          open('/proc/self/status').read())
        if match:
            res = bin(int(match.group(1).replace(',', ''), 16)).count('1')
            if res > 0:
                return res
    except IOError:
        LOG.debug("Could not get the number of allowed CPUs")

    # http://code.google.com/p/psutil/
    try:
        import psutil
        return psutil.cpu_count()  # psutil.NUM_CPUS on old versions
    except (ImportError, AttributeError):
        LOG.debug("Could not get the number of allowed CPUs")

    # POSIX
    try:
        res = int(os.sysconf('SC_NPROCESSORS_ONLN'))

        if res > 0:
            return res
    except (AttributeError, ValueError):
        LOG.debug("Could not get the number of allowed CPUs")

    # Linux
    try:
        res = open('/proc/cpuinfo').read().count('processor\t:')

        if res > 0:
            return res
    except IOError:
        LOG.debug("Could not get the number of allowed CPUs")

    raise Exception('Can not determine number of CPUs on this system')
78270
def read_stat():
    
    data = []
    with open("/proc/stat", "rb") as stat_file:
        for line in stat_file:
            cpu_stat = line.split()
            if cpu_stat[0][:3] != b"cpu":
                break
            # First cpu line is aggregation of following lines, skip it
            if len(cpu_stat[0]) == 3:
                continue
            data.append(
                {
                    "times": {
                        "user": int(cpu_stat[1]),
                        "nice": int(cpu_stat[2]),
                        "sys": int(cpu_stat[3]),
                        "idle": int(cpu_stat[4]),
                        "irq": int(cpu_stat[6]),
                    }
                }
            )
    return data
1104838
def cpustats():
    '''
    
    '''
    # Tries to gather information similar to that returned by a Linux machine
    # Avoid using WMI as there's a lot of overhead

    # Time related info
    user, system, idle, interrupt, dpc = psutil.cpu_times()
    cpu = {'user': user,
           'system': system,
           'idle': idle,
           'irq': interrupt,
           'dpc': dpc}
    # Count related info
    ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
    intr = {'irqs': {'irqs': [],
                     'total': interrupts}}
    soft_irq = {'softirqs': [],
               'total': soft_interrupts}
    return {'btime': psutil.boot_time(),
            'cpu': cpu,
            'ctxt': ctx_switches,
            'intr': intr,
            'processes': len(psutil.pids()),
            'softirq': soft_irq,
            'syscalls': sys_calls}