Read number of CPUs from environment or fallback to the _private_ configuration property
Useful for determining the number of processes to fork.
173605
function num_of_cpus() {
  try {
    if(process.env['OMP_NUM_THREADS']) {
      return process.env['OMP_NUM_THREADS'];
    }

    return Math.ceil(jsonConfig.info.limits.cpu);
  } catch (err) {
    throw new Error('Could not get number of cpus');
  }
}
207509
def count_processors():
    """"""
    if 'SLURM_NTASKS' in os.environ: return int(os.environ['SLURM_NTASKS'])
    elif 'SLURM_JOB_CPUS_PER_NODE' in os.environ:
         text = os.environ['SLURM_JOB_CPUS_PER_NODE']
         if is_integer(text): return int(text)
         else:
            n, N = re.findall("([1-9]+)\(x([1-9]+)\)", text)[0]
            return int(n) * int(N)
    else: return multiprocessing.cpu_count()
1229743
def get_cpu_info():
	'''
	
	'''

	import json

	output = get_cpu_info_json()

	# Convert JSON to Python with non unicode strings
	output = json.loads(output, object_hook = _utf_to_str)

	return output
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)()
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
101309
def process_info(pid=None):
    '''
    '''
    if psutil is None:  # pragma    nocover
        return {}
    pid = pid or os.getpid()
    try:
        p = psutil.Process(pid)
    # this fails on platforms which don't allow multiprocessing
    except psutil.NoSuchProcess:  # pragma    nocover
        return {}
    else:
        mem = p.memory_info()
        return {'memory': convert_bytes(mem.rss),
                'memory_virtual': convert_bytes(mem.vms),
                'cpu_percent': p.cpu_percent(),
                'nice': p.nice(),
                'num_threads': p.num_threads()}
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")
253871
def _parallel_exec(self, hosts):
        '''  '''
        if not hosts:
            return
        p = multiprocessing.Pool(self.forks)
        results = []
        #results = p.map(multiprocessing_runner, hosts) # can't handle keyboard interrupt
        results = p.map_async(multiprocessing_runner, hosts).get(9999999)
        p.close()
        p.join()
        return results
768368
def ncores_used(self):
        
        return sum(task.manager.num_cores for task in self if task.status == task.S_RUN)
1214365
def detect_system_properties(arch)
      parts = (arch || architecture).split('-', 2)

      if parts.length == 1
        @cpu, system = nil, parts.shift
      else
        @cpu, system = *parts
      end
      @os, @version = *find_os_and_version(system)
      [@cpu, @os, @version]
    end
1111437
def Cpu():
    
    cpu = 'Unknown'

    try:
        cpu = str(multiprocessing.cpu_count())
    except Exception as e:  # pragma: no cover
        logger.error("Can't access CPU count' " + str(e))
    return cpu
1289356
def cpuinfo():
    ''' 

    '''

    cpuinfo=OrderedDict()
    procinfo=OrderedDict()

    nprocs = 0
    with open('/proc/cpuinfo') as f:
        for line in f:
            if not line.strip():
                # end of one processor
                cpuinfo['proc%s' % nprocs] = procinfo
                nprocs=nprocs+1
                # Reset
                procinfo=OrderedDict()
            else:
                if len(line.split(':')) == 2:
                    procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()
                else:
                    procinfo[line.split(':')[0].strip()] = ''
            
    return cpuinfo
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])
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
226269
def process_affinity(affinity=None):
    
    if affinity is not None:
        affinity = CPUSet(affinity)
        if not affinity.issubset(system_affinity()):
            raise ValueError("unknown cpus: %s" % affinity)
    return system_affinity()
1281116
def get_public(self):
        '''
        
        '''
        node = self.node.find('public')
        if node is not None:
            return Cpublic(node=node)
        else:
            return None
4352
private static CpuAcctMetric parse(final List<String> lines)
  {
    // File has a header. We skip it
    // See src/test/resources/cpuacct.usage_all for an example
    final int ncpus = lines.size() - 1;
    final long[] usrTime = new long[ncpus];
    final long[] sysTime = new long[ncpus];
    for (int i = 1; i < lines.size(); i++) {
      final String[] splits = lines.get(i).split(CgroupUtil.SPACE_MATCH, 3);
      if (splits.length != 3) {
        throw new RE("Error parsing [%s]", lines.get(i));
      }
      final int cpuNum = Integer.parseInt(splits[0]);
      usrTime[cpuNum] = Long.parseLong(splits[1]);
      sysTime[cpuNum] = Long.parseLong(splits[2]);
    }
    return new CpuAcctMetric(usrTime, sysTime);
  }