Ascertain the number of cpus allowed for each high-compte job instance (bwa, star, rsem, phlat).

    :param max_cores: The user-specified max
    :return: The number of cpus allowed for each high-compte job instance
    :rtype: int
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
935509
def ncores_allocated(self):
        
        return sum(task.manager.num_cores for task in self if task.status in [task.S_SUB, task.S_RUN])
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
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)
1216093
public void setProcessorMaxThreads(int maxThreads) {
        if (processor.getCorePoolSize() > maxThreads) {
            processor.setCorePoolSize(maxThreads);
        }
        processor.setMaximumPoolSize(maxThreads);
    }
678164
def num_unused_cpus(thresh=10):
    
    import psutil
    cpu_usage = psutil.cpu_percent(percpu=True)
    return sum([p < thresh for p in cpu_usage])
1316343
def sys_maxfd():
    
    maxfd = None
    try:
        maxfd = int(resource.getrlimit(resource.RLIMIT_NOFILE)[0])
        if maxfd == resource.RLIM_INFINITY:                                                     # pragma: no cover
            maxfd = None
    except: pass
    if maxfd is None:
        maxfd = sys_maxfd.fallback_maxfd
    return maxfd
1097837
def _init_num_threads():
    
    # Any platform-specific short-circuits
    if 'sparc' in platform.machine():
        log.warning('The number of threads have been set to 1 because problems related '
                  'to threading have been reported on some sparc machine. '
                  'The number of threads can be changed using the "set_num_threads" '
                  'function.')
        set_num_threads(1)
        return 1

    env_configured = False
    n_cores = detect_number_of_cores()
    if 'NUMEXPR_MAX_THREADS' in os.environ:
        # The user has configured NumExpr in the expected way, so suppress logs.
        env_configured = True
        n_cores = MAX_THREADS
    else:
        # The use has not set 'NUMEXPR_MAX_THREADS', so likely they have not 
        # configured NumExpr as desired, so we emit info logs.
        if n_cores > MAX_THREADS:
            log.info('Note: detected %d virtual cores but NumExpr set to maximum of %d, check "NUMEXPR_MAX_THREADS" environment variable.'%(n_cores, MAX_THREADS))
        if n_cores > 8:
            # The historical 'safety' limit.
            log.info('Note: NumExpr detected %d cores but "NUMEXPR_MAX_THREADS" not set, so enforcing safe limit of 8.'%n_cores)
            n_cores = 8

    # Now we check for 'NUMEXPR_NUM_THREADS' or 'OMP_NUM_THREADS' to set the 
    # actual number of threads used.
    if 'NUMEXPR_NUM_THREADS' in os.environ:
        requested_threads = int(os.environ['NUMEXPR_NUM_THREADS'])
    elif 'OMP_NUM_THREADS' in os.environ:
        requested_threads = int(os.environ['OMP_NUM_THREADS'])
    else:
        requested_threads = n_cores
        if not env_configured:
            log.info('NumExpr defaulting to %d threads.'%n_cores)

    # The C-extension function performs its own checks against `MAX_THREADS`
    set_num_threads(requested_threads)
    return requested_threads
749083
def configure(cls: typing.Type["ThreadPooled"], max_workers: typing.Optional[int] = None) -> None:
        
        if isinstance(cls.__executor, ThreadPoolExecutor):
            if cls.__executor.max_workers == max_workers:
                return
            cls.__executor.shutdown()

        cls.__executor = ThreadPoolExecutor(max_workers=max_workers)
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
147359
public void setMaxNumberOfThreadsPerTask(Integer maxNumberOfThreadsPerTask) {
        if(maxNumberOfThreadsPerTask<0) {
            throw new IllegalArgumentException("The max number of threads can not be negative.");
        }
        else if(maxNumberOfThreadsPerTask==0) {
            this.maxNumberOfThreadsPerTask = AVAILABLE_PROCESSORS;
        }
        else {
            this.maxNumberOfThreadsPerTask = Math.min(maxNumberOfThreadsPerTask, 4*AVAILABLE_PROCESSORS);
        }
    }
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
1087402
public int getMaxQueuedConnections() {
	return getThreadPool() == null ? -1 :
	    ((getThreadPool().getQueue() instanceof ArrayBlockingQueue) ?
	     ((ArrayBlockingQueue)getThreadPool().getQueue()).size() +
	     ((ArrayBlockingQueue)getThreadPool().getQueue()).remainingCapacity() : -1);	     
    }
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
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()
768368
def ncores_used(self):
        
        return sum(task.manager.num_cores for task in self if task.status == task.S_RUN)
688179
def _add_cpu_percent(self, cur_read):
        
        for executor_id, cur_data in cur_read.items():
            stats = cur_data['statistics']
            cpus_limit = stats.get('cpus_limit')
            cpus_utilisation = stats.get('cpus_utilisation')
            if cpus_utilisation and cpus_limit != 0:
                stats['cpus_percent'] = cpus_utilisation / cpus_limit