Returns the CPU info gathered from lscpu.
	Returns {} if lscpu is not found.
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 {}
1091851
def _get_cpu_info_from_ibm_pa_features():
	'''
	
	'''
	try:
		# Just return {} if there is no lsprop
		if not DataSource.has_ibm_pa_features():
			return {}

		# If ibm,pa-features fails return {}
		returncode, output = DataSource.ibm_pa_features()
		if output == None or returncode != 0:
			return {}

		# Filter out invalid characters from output
		value = output.split("ibm,pa-features")[1].lower()
		value = [s for s in value if s in list('0123456789abcfed')]
		value = ''.join(value)

		# Get data converted to Uint32 chunks
		left = int(value[0 : 8], 16)
		right = int(value[8 : 16], 16)

		# Get the CPU flags
		flags = {
			# Byte 0
			'mmu' : _is_bit_set(left, 0),
			'fpu' : _is_bit_set(left, 1),
			'slb' : _is_bit_set(left, 2),
			'run' : _is_bit_set(left, 3),
			#'reserved' : _is_bit_set(left, 4),
			'dabr' : _is_bit_set(left, 5),
			'ne' : _is_bit_set(left, 6),
			'wtr' : _is_bit_set(left, 7),

			# Byte 1
			'mcr' : _is_bit_set(left, 8),
			'dsisr' : _is_bit_set(left, 9),
			'lp' : _is_bit_set(left, 10),
			'ri' : _is_bit_set(left, 11),
			'dabrx' : _is_bit_set(left, 12),
			'sprg3' : _is_bit_set(left, 13),
			'rislb' : _is_bit_set(left, 14),
			'pp' : _is_bit_set(left, 15),

			# Byte 2
			'vpm' : _is_bit_set(left, 16),
			'dss_2.05' : _is_bit_set(left, 17),
			#'reserved' : _is_bit_set(left, 18),
			'dar' : _is_bit_set(left, 19),
			#'reserved' : _is_bit_set(left, 20),
			'ppr' : _is_bit_set(left, 21),
			'dss_2.02' : _is_bit_set(left, 22),
			'dss_2.06' : _is_bit_set(left, 23),

			# Byte 3
			'lsd_in_dscr' : _is_bit_set(left, 24),
			'ugr_in_dscr' : _is_bit_set(left, 25),
			#'reserved' : _is_bit_set(left, 26),
			#'reserved' : _is_bit_set(left, 27),
			#'reserved' : _is_bit_set(left, 28),
			#'reserved' : _is_bit_set(left, 29),
			#'reserved' : _is_bit_set(left, 30),
			#'reserved' : _is_bit_set(left, 31),

			# Byte 4
			'sso_2.06' : _is_bit_set(right, 0),
			#'reserved' : _is_bit_set(right, 1),
			#'reserved' : _is_bit_set(right, 2),
			#'reserved' : _is_bit_set(right, 3),
			#'reserved' : _is_bit_set(right, 4),
			#'reserved' : _is_bit_set(right, 5),
			#'reserved' : _is_bit_set(right, 6),
			#'reserved' : _is_bit_set(right, 7),

			# Byte 5
			'le' : _is_bit_set(right, 8),
			'cfar' : _is_bit_set(right, 9),
			'eb' : _is_bit_set(right, 10),
			'lsq_2.07' : _is_bit_set(right, 11),
			#'reserved' : _is_bit_set(right, 12),
			#'reserved' : _is_bit_set(right, 13),
			#'reserved' : _is_bit_set(right, 14),
			#'reserved' : _is_bit_set(right, 15),

			# Byte 6
			'dss_2.07' : _is_bit_set(right, 16),
			#'reserved' : _is_bit_set(right, 17),
			#'reserved' : _is_bit_set(right, 18),
			#'reserved' : _is_bit_set(right, 19),
			#'reserved' : _is_bit_set(right, 20),
			#'reserved' : _is_bit_set(right, 21),
			#'reserved' : _is_bit_set(right, 22),
			#'reserved' : _is_bit_set(right, 23),

			# Byte 7
			#'reserved' : _is_bit_set(right, 24),
			#'reserved' : _is_bit_set(right, 25),
			#'reserved' : _is_bit_set(right, 26),
			#'reserved' : _is_bit_set(right, 27),
			#'reserved' : _is_bit_set(right, 28),
			#'reserved' : _is_bit_set(right, 29),
			#'reserved' : _is_bit_set(right, 30),
			#'reserved' : _is_bit_set(right, 31),
		}

		# Get a list of only the flags that are true
		flags = [k for k, v in flags.items() if v]
		flags.sort()

		info = {
			'flags' : flags
		}
		info = {k: v for k, v in info.items() if v}

		return info
	except:
		return {}
762209
def _node_info(conn):
    '''
    
    '''
    raw = conn.getInfo()
    info = {'cpucores': raw[6],
            'cpumhz': raw[3],
            'cpumodel': six.text_type(raw[0]),
            'cpus': raw[2],
            'cputhreads': raw[7],
            'numanodes': raw[4],
            'phymemory': raw[1],
            'sockets': raw[5]}
    return info
841351
function cpuAverage() {
      //Initialise sum of idle and time of cores and fetch CPU info
      var totalIdle = 0, totalTick = 0;
      var cpus = os.cpus();

      //Loop through CPU cores
      for(var i = 0, len = cpus.length; i < len; i++) {

        //Select CPU core
        var cpu = cpus[i];

        //Total up the time in the cores tick
        for(type in cpu.times) {
          totalTick += cpu.times[type];
       }

        //Total up the idle time of the core
        totalIdle += cpu.times.idle;
      }

      //Return the average Idle and Tick times
      return {idle: totalIdle / cpus.length,  total: totalTick / cpus.length};
    }
216342
def get(cls):
        
        stats = {}
        cur_time = time.time()
        # minimum interval for getting CPU and memory statistics
        if cur_time < cls._last_measurement or \
           cur_time > cls._last_measurement + 1.9:
            cls._last_measurement = cur_time
            # Non blocking call to get cpu usage. First call will return 0
            cls._last_cpu_percent = psutil.cpu_percent(interval=None)
            cls._last_mem_percent = psutil.virtual_memory().percent
        stats["cpu_usage_percent"] = cls._last_cpu_percent
        stats["memory_usage_percent"] = cls._last_mem_percent
        return stats
1069718
def _linux_cpudata():
    '''
    
    '''
    # Provides:
    #   num_cpus
    #   cpu_model
    #   cpu_flags
    grains = {}
    cpuinfo = '/proc/cpuinfo'
    # Parse over the cpuinfo file
    if os.path.isfile(cpuinfo):
        with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
            grains['num_cpus'] = 0
            for line in _fp:
                comps = line.split(':')
                if not len(comps) > 1:
                    continue
                key = comps[0].strip()
                val = comps[1].strip()
                if key == 'processor':
                    grains['num_cpus'] += 1
                elif key == 'model name':
                    grains['cpu_model'] = val
                elif key == 'flags':
                    grains['cpu_flags'] = val.split()
                elif key == 'Features':
                    grains['cpu_flags'] = val.split()
                # ARM support - /proc/cpuinfo
                #
                # Processor       : ARMv6-compatible processor rev 7 (v6l)
                # BogoMIPS        : 697.95
                # Features        : swp half thumb fastmult vfp edsp java tls
                # CPU implementer : 0x41
                # CPU architecture: 7
                # CPU variant     : 0x0
                # CPU part        : 0xb76
                # CPU revision    : 7
                #
                # Hardware        : BCM2708
                # Revision        : 0002
                # Serial          : 00000000
                elif key == 'Processor':
                    grains['cpu_model'] = val.split('-')[0]
                    grains['num_cpus'] = 1
    if 'num_cpus' not in grains:
        grains['num_cpus'] = 0
    if 'cpu_model' not in grains:
        grains['cpu_model'] = 'Unknown'
    if 'cpu_flags' not in grains:
        grains['cpu_flags'] = []
    return grains
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
922788
def detect_number_of_cores():
    
    # Linux, Unix and MacOS:
    if hasattr(os, "sysconf"):
        if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
            # Linux & Unix:
            ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
            if isinstance(ncpus, int) and ncpus > 0:
                return ncpus
        else:  # OSX:
            return int(subprocess.check_output(["sysctl", "-n", "hw.ncpu"]))
    # Windows:
    try:
        ncpus = int(os.environ.get("NUMBER_OF_PROCESSORS", ""))
        if ncpus > 0:
            return ncpus
    except ValueError:
        pass
    return 1
1076062
def get_processor_name():
    
    if platform.system() == "Linux":
        with open("/proc/cpuinfo", "rb") as cpuinfo:
            all_info = cpuinfo.readlines()
            for line in all_info:
                if b'model name' in line:
                    return re.sub(b'.*model name.*:', b'', line, 1)

    return platform.processor()
748801
def _sunos_cpudata():
    '''
    
    '''
    # Provides:
    #   cpuarch
    #   num_cpus
    #   cpu_model
    #   cpu_flags
    grains = {}
    grains['cpu_flags'] = []

    grains['cpuarch'] = __salt__['cmd.run']('isainfo -k')
    psrinfo = '/usr/sbin/psrinfo 2>/dev/null'
    grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines())
    kstat_info = 'kstat -p cpu_info:*:*:brand'
    for line in __salt__['cmd.run'](kstat_info).splitlines():
        match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line)
        if match:
            grains['cpu_model'] = match.group(2)
    isainfo = 'isainfo -n -v'
    for line in __salt__['cmd.run'](isainfo).splitlines():
        match = re.match(r'^\s+(.+)', line)
        if match:
            cpu_flags = match.group(1).split()
            grains['cpu_flags'].extend(cpu_flags)

    return grains
1062846
def getProcessStats(self):
        
        info_dict = {}
        try:
            fp = open(cpustatFile, 'r')
            data = fp.read()
            fp.close()
        except:
            raise IOError('Failed reading stats from file: %s' % cpustatFile)
        for line in data.splitlines():
            arr = line.split()
            if len(arr) > 1 and arr[0] in ('ctxt', 'intr', 'softirq',
                                           'processes', 'procs_running', 
                                           'procs_blocked'):
                info_dict[arr[0]] = arr[1]
        return info_dict
558156
def get_cpu_usage(user=None, ignore_self=True):
    
    pid = os.getpid()
    cmd = "ps aux"
    output = getoutput(cmd)
    total = 0
    largest_process = 0
    largest_process_name = None
    for row in output.split('\n')[1:]:
        row = row.split()
        if row[1] == str(pid) and ignore_self:
            continue
        if user is None or user == row[0]:
            cpu = decimal.Decimal(row[2])
            if cpu > total:
                largest_process = cpu
                largest_process_name = ' '.join(row[10:len(row)])
            total += decimal.Decimal(row[2])
    return total, largest_process, largest_process_name
1238757
def update_local(self):
        """"""
        # Grab CPU stats using psutil's cpu_percent and cpu_times_percent
        # Get all possible values for CPU stats: user, system, idle,
        # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+)
        # The following stats are returned by the API but not displayed in the UI:
        # softirq (Linux), guest (Linux 2.6.24+), guest_nice (Linux 3.2.0+)

        # Init new stats
        stats = self.get_init_value()

        stats['total'] = cpu_percent.get()
        cpu_times_percent = psutil.cpu_times_percent(interval=0.0)
        for stat in ['user', 'system', 'idle', 'nice', 'iowait',
                     'irq', 'softirq', 'steal', 'guest', 'guest_nice']:
            if hasattr(cpu_times_percent, stat):
                stats[stat] = getattr(cpu_times_percent, stat)

        # Additional CPU stats (number of events not as a %; psutil>=4.1.0)
        # ctx_switches: number of context switches (voluntary + involuntary) per second
        # interrupts: number of interrupts per second
        # soft_interrupts: number of software interrupts per second. Always set to 0 on Windows and SunOS.
        # syscalls: number of system calls since boot. Always set to 0 on Linux.
        cpu_stats = psutil.cpu_stats()
        # By storing time data we enable Rx/s and Tx/s calculations in the
        # XML/RPC API, which would otherwise be overly difficult work
        # for users of the API
        time_since_update = getTimeSinceLastUpdate('cpu')

        # Previous CPU stats are stored in the cpu_stats_old variable
        if not hasattr(self, 'cpu_stats_old'):
            # First call, we init the cpu_stats_old var
            self.cpu_stats_old = cpu_stats
        else:
            for stat in cpu_stats._fields:
                if getattr(cpu_stats, stat) is not None:
                    stats[stat] = getattr(cpu_stats, stat) - getattr(self.cpu_stats_old, stat)

            stats['time_since_update'] = time_since_update

            # Core number is needed to compute the CTX switch limit
            stats['cpucore'] = self.nb_log_core

            # Save stats to compute next step
            self.cpu_stats_old = cpu_stats

        return stats
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)
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 {}
118583
def physical_cpus():
    
    if platform.system() == 'Darwin':
        ncores = subprocess.check_output(
            ['/usr/sbin/sysctl', '-n', 'hw.ncpu'], shell=False
        )
        return int(ncores.strip())

    sockets = set()
    with open('/proc/cpuinfo') as istr:
        for line in istr:
            if line.startswith('physical id'):
                sockets.add(line.split(':')[-1].strip())
    return len(sockets)
1094991
def get_num_processors():
    
    # try different strategies and use first one that succeeeds
    try:
        return os.cpu_count()  # Py3 only
    except AttributeError:
        pass
    try:
        import multiprocessing
        return multiprocessing.cpu_count()
    except ImportError:  # no multiprocessing?
        pass
    except NotImplementedError:
        # multiprocessing cannot determine CPU count
        pass
    try:
        from subprocess32 import check_output
        ncpus = check_output('nproc')
        return int(ncpus)
    except CalledProcessError:  # no `/usr/bin/nproc`
        pass
    except (ValueError, TypeError):
        # unexpected output from `nproc`
        pass
    except ImportError:  # no subprocess32?
        pass
    try:
        from subprocess import check_output
        ncpus = check_output('nproc')
        return int(ncpus)
    except CalledProcessError:  # no `/usr/bin/nproc`
        pass
    except (ValueError, TypeError):
        # unexpected output from `nproc`
        pass
    except ImportError:  # no subprocess.check_call (Py 2.6)
        pass
    raise RuntimeError("Cannot determine number of processors")