Get number of CPUs usable by the current process.

    Takes into consideration cpusets restrictions.

    Returns
    -------
    int
350370
def usable_cpu_count():
    
    try:
        result = len(os.sched_getaffinity(0))
    except AttributeError:
        try:
            result = len(psutil.Process().cpu_affinity())
        except AttributeError:
            result = os.cpu_count()
    return result
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
513815
def _collect_cpu_info(run_info):
  """"""
  cpu_info = {}

  cpu_info["num_cores"] = multiprocessing.cpu_count()

  # Note: cpuinfo is not installed in the TensorFlow OSS tree.
  # It is installable via pip.
  import cpuinfo    # pylint: disable=g-import-not-at-top

  info = cpuinfo.get_cpu_info()
  cpu_info["cpu_info"] = info["brand"]
  cpu_info["mhz_per_cpu"] = info["hz_advertised_raw"][0] / 1.0e6

  run_info["machine_config"]["cpu_info"] = cpu_info
810518
def get_processors(self):
        ""
        procs_x,procs_y = listify(self.train.x._processor),listify(self.train.y._processor)
        xp = ifnone(self.train.x.processor, [p(ds=self.train.x) for p in procs_x])
        yp = ifnone(self.train.y.processor, [p(ds=self.train.y) for p in procs_y])
        return xp,yp
656651
def infer_process_count(self):
        '''
        '''

        try:
            self.processes = multiprocessing.cpu_count()
        except NotImplementedError:
            self._logger.log(
                'error',
                'Could infer CPU count, setting number of processes back to 4'
            )
            self.processes = 4
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
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}
341763
def _get_num_parallel_threads(max_threads, num_cores, mem_available_mb):
    '''
    
    '''
    return min(max_threads, num_cores, max(int(mem_available_mb/1200), 1))
1284707
def cpustats():
    '''
    
    '''
    def linux_cpustats():
        '''
        linux specific implementation of cpustats
        '''
        ret = {}
        try:
            with salt.utils.files.fopen('/proc/stat', 'r') as fp_:
                stats = salt.utils.stringutils.to_unicode(fp_.read())
        except IOError:
            pass
        else:
            for line in stats.splitlines():
                if not line:
                    continue
                comps = line.split()
                if comps[0] == 'cpu':
                    ret[comps[0]] = {'idle': _number(comps[4]),
                                     'iowait': _number(comps[5]),
                                     'irq': _number(comps[6]),
                                     'nice': _number(comps[2]),
                                     'softirq': _number(comps[7]),
                                     'steal': _number(comps[8]),
                                     'system': _number(comps[3]),
                                     'user': _number(comps[1])}
                elif comps[0] == 'intr':
                    ret[comps[0]] = {'total': _number(comps[1]),
                                     'irqs': [_number(x) for x in comps[2:]]}
                elif comps[0] == 'softirq':
                    ret[comps[0]] = {'total': _number(comps[1]),
                                     'softirqs': [_number(x) for x in comps[2:]]}
                else:
                    ret[comps[0]] = _number(comps[1])
        return ret

    def freebsd_cpustats():
        '''
        freebsd specific implementation of cpustats
        '''
        vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
        vm0 = vmstat[0].split()
        cpu0loc = vm0.index('cpu0')
        vm1 = vmstat[1].split()
        usloc = vm1.index('us')
        vm2 = vmstat[2].split()
        cpuctr = 0
        ret = {}
        for cpu in vm0[cpu0loc:]:
            ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
                        'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
                        'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
            cpuctr += 1
        return ret

    def sunos_cpustats():
        '''
        sunos specific implementation of cpustats
        '''
        mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
        fields = mpstat[0].split()
        ret = {}
        for cpu in mpstat:
            if cpu.startswith('CPU'):
                continue
            cpu = cpu.split()
            ret[_number(cpu[0])] = {}
            for i in range(1, len(fields)-1):
                ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
        return ret

    def aix_cpustats():
        '''
        AIX specific implementation of cpustats
        '''
        ret = {}
        ret['mpstat'] = []
        procn = None
        fields = []
        for line in __salt__['cmd.run']('mpstat -a').splitlines():
            if not line:
                continue
            procn = len(ret['mpstat'])
            if line.startswith('System'):
                comps = line.split(':')
                ret['mpstat'].append({})
                ret['mpstat'][procn]['system'] = {}
                cpu_comps = comps[1].split()
                for i in range(0, len(cpu_comps)):
                    cpu_vals = cpu_comps[i].split('=')
                    ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]

            if line.startswith('cpu'):
                fields = line.split()
                continue

            if fields:
                cpustat = line.split()
                ret[_number(cpustat[0])] = {}
                for i in range(1, len(fields)-1):
                    ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])

        return ret

    def openbsd_cpustats():
        '''
        openbsd specific implementation of cpustats
        '''
        systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
        fields = systat[3].split()
        ret = {}
        for cpu in systat[4:]:
            cpu_line = cpu.split()
            cpu_idx = cpu_line[0]
            ret[cpu_idx] = {}

            for idx, field in enumerate(fields[1:]):
                ret[cpu_idx][field] = cpu_line[idx+1]

        return ret

    # dict that return a function that does the right thing per platform
    get_version = {
        'Linux': linux_cpustats,
        'FreeBSD': freebsd_cpustats,
        'OpenBSD': openbsd_cpustats,
        'SunOS': sunos_cpustats,
        'AIX': aix_cpustats,
    }

    errmsg = 'This method is unsupported on the current operating system!'
    return get_version.get(__grains__['kernel'], lambda: errmsg)()
761067
def ascertain_cpu_share(max_cores=None):
    
    # Ascertain the number of available CPUs. Jobs will be given fractions of this value.
    num_cores = cpu_count()
    # The minimum number of cpus should be at least 6 if possible
    min_cores = min(num_cores, 6)
    cpu_share = max(num_cores / 2, min_cores)
    if max_cores is not None:
        cpu_share = min(cpu_share, max_cores)
    return cpu_share
248235
def cpu_usage
      result = run("cgroup", "cpuacct.usage").to_s.strip
      result.empty? ? nil : Float("%.4f" % (result.to_i / 1E9))
    end
1326462
def set_cpu_affinity(n, process_ids, actual=not Conf.TESTING):
    
    # check if we have the psutil module
    if not psutil:
        logger.warning('Skipping cpu affinity because psutil was not found.')
        return
    # check if the platform supports cpu_affinity
    if actual and not hasattr(psutil.Process(process_ids[0]), 'cpu_affinity'):
        logger.warning('Faking cpu affinity because it is not supported on this platform')
        actual = False
    # get the available processors
    cpu_list = list(range(psutil.cpu_count()))
    # affinities of 0 or gte cpu_count, equals to no affinity
    if not n or n >= len(cpu_list):
        return
    # spread the workers over the available processors.
    index = 0
    for pid in process_ids:
        affinity = []
        for k in range(n):
            if index == len(cpu_list):
                index = 0
            affinity.append(cpu_list[index])
            index += 1
        if psutil.pid_exists(pid):
            p = psutil.Process(pid)
            if actual:
                p.cpu_affinity(affinity)
            logger.info(_('{} will use cpu {}').format(pid, affinity))
390018
public int getTotalCpuPercent() {
		if (invalidMonitor.get()) {
			return 0;
		}
		long now = System.currentTimeMillis();
		int cpu;
		synchronized (Monitor.class) {
			if (now - cpuDetectedAt > cacheTimeout) {
				try {
					cachedCPU = detectTotalCpuPercent();
				} catch (Throwable cause) {
					logger.info("Unable to detect CPU usage!", cause);
					invalidMonitor.set(true);
				}
				cpuDetectedAt = now;
			}
			cpu = cachedCPU;
		}
		return cpu;
	}
1350089
def memory_usage():
    
    try:
        import psutil
        import os
    except ImportError:
        return _memory_usage_ps()

    process = psutil.Process(os.getpid())
    mem = process.memory_info()[0] / float(2 ** 20)
    return mem
437074
def _windows_cpudata():
    '''
    
    '''
    # Provides:
    #   num_cpus
    #   cpu_model
    grains = {}
    if 'NUMBER_OF_PROCESSORS' in os.environ:
        # Cast to int so that the logic isn't broken when used as a
        # conditional in templating. Also follows _linux_cpudata()
        try:
            grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
        except ValueError:
            grains['num_cpus'] = 1
    grains['cpu_model'] = salt.utils.win_reg.read_value(
        hive="HKEY_LOCAL_MACHINE",
        key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
        vname="ProcessorNameString").get('vdata')
    return grains
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
886851
def _add_cpu_usage(self, cur_read):
        

        for executor_id, cur_data in cur_read.items():
            if executor_id in self.executors_prev_read:
                prev_data = self.executors_prev_read[executor_id]
                prev_stats = prev_data['statistics']
                cur_stats = cur_data['statistics']
                # from sum of current cpus time subtract previous sum
                cpus_time_diff_s = cur_stats['cpus_user_time_secs']
                cpus_time_diff_s += cur_stats['cpus_system_time_secs']
                cpus_time_diff_s -= prev_stats['cpus_user_time_secs']
                cpus_time_diff_s -= prev_stats['cpus_system_time_secs']
                ts_diff = cur_stats['timestamp'] - prev_stats['timestamp']
                if ts_diff != 0:
                    cur_stats['cpus_utilisation'] = cpus_time_diff_s / ts_diff

            self.executors_prev_read[executor_id] = cur_read[executor_id]