Returns the total CPU usage for all available cores.

    :param user: If given, returns only the total CPU usage of all processes
      for the given user.
    :param ignore_self: If ``True`` the process that runs this script will
      be ignored.
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
268308
def get_passenger_cpu_usage(self, dict_stats):
        
        try:
            proc1 = subprocess.Popen(
                ["top", "-b", "-n", "2"],
                stdout=subprocess.PIPE)
            (std_out, std_err) = proc1.communicate()
        except OSError:
            return (-1)

        re_lspaces = re.compile("^\s*")
        re_digit = re.compile("^\d")
        overall_cpu = 0
        for raw_line in std_out.splitlines():
            line = re_lspaces.sub("", raw_line)
            if not re_digit.match(line):
                continue

            line_splitted = line.split()
            if line_splitted[0] in dict_stats["apache_procs"]:
                overall_cpu += float(line_splitted[8])
            elif line_splitted[0] in dict_stats["nginx_procs"]:
                overall_cpu += float(line_splitted[8])
            elif line_splitted[0] in dict_stats["passenger_procs"]:
                overall_cpu += float(line_splitted[8])

        return overall_cpu
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))
1296232
function getFullLoad() {

  return new Promise((resolve) => {
    process.nextTick(() => {

      const cpus = os.cpus();
      let totalUser = 0;
      let totalSystem = 0;
      let totalNice = 0;
      let totalIrq = 0;
      let totalIdle = 0;

      for (let i = 0, len = cpus.length; i < len; i++) {
        const cpu = cpus[i].times;
        totalUser += cpu.user;
        totalSystem += cpu.sys;
        totalNice += cpu.nice;
        totalIrq += cpu.irq;
        totalIdle += cpu.idle;
      }
      let totalTicks = totalIdle + totalIrq + totalNice + totalSystem + totalUser;
      let result = (totalTicks - totalIdle) / totalTicks * 100.0;

      resolve(result);
    });
  });
}
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()
662264
def _queue_processor(self)->None:
        ""
        while not self.stop_request.isSet():
            while not self.queue.empty():
                if self.stop_request.isSet(): return
                request = self.queue.get()
                request.write()
            sleep(0.2)
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
418601
def set_cpus(self, cpus=0):
        
        from multiprocessing import cpu_count

        max_cpus = cpu_count()
        if not 0 < cpus < max_cpus:
            cpus = max_cpus
        self.add_option("--cpus", default=cpus, type="int",
                     help="Number of CPUs to use, 0=unlimited [default: %default]")
1104439
def consumer_stats_counter():
        
        return {
            process.Process.ERROR: 0,
            process.Process.PROCESSED: 0,
            process.Process.REDELIVERED: 0
        }
1313075
def _memory_usage(self, pid='self', category="hwm", container=None):
        
        if container:
            # TODO: Put some debug output here with switch to Logger
            # since this is relatively untested.
            cmd = "docker stats " + container + " --format '{{.MemUsage}}' --no-stream"
            mem_use_str = subprocess.check_output(cmd, shell=True)
            mem_use = mem_use_str.split("/")[0].split()
            
            mem_num = re.findall('[\d\.]+', mem_use_str.split("/")[0])[0]
            mem_scale = re.findall('[A-Za-z]+', mem_use_str.split("/")[0])[0]

            #print(mem_use_str, mem_num, mem_scale)
            mem_num = float(mem_num)
            if mem_scale == "GiB":
                return mem_num * 1e6
            elif mem_scale == "MiB":
                return mem_num * 1e3
            elif mem_scale == "KiB":
                return mem_num
            else:
                # What type is this?
                return 0

        # Thanks Martin Geisler:
        status = None
        result = {'peak': 0, 'rss': 0, 'hwm': 0}
        
        try:
            # This will only work on systems with a /proc file system
            # (like Linux).
            # status = open('/proc/self/status')
            proc_spot = '/proc/%s/status' % pid
            status = open(proc_spot)
            for line in status:
                parts = line.split()
                key = parts[0][2:-1].lower()
                if key in result:
                    result[key] = int(parts[1])
        except:
            return 0

        finally:
            if status is not None:
                status.close()
        # print(result[category])
        return result[category]
739706
def UpdateProtoResources(self, status):
    """"""
    user_cpu = status.cpu_time_used.user_cpu_time
    system_cpu = status.cpu_time_used.system_cpu_time
    self.context.client_resources.cpu_usage.user_cpu_time += user_cpu
    self.context.client_resources.cpu_usage.system_cpu_time += system_cpu

    user_cpu_total = self.context.client_resources.cpu_usage.user_cpu_time
    system_cpu_total = self.context.client_resources.cpu_usage.system_cpu_time

    self.context.network_bytes_sent += status.network_bytes_sent

    if self.runner_args.cpu_limit:
      if self.runner_args.cpu_limit < (user_cpu_total + system_cpu_total):
        # We have exceeded our limit, stop this flow.
        raise FlowRunnerError("CPU limit exceeded.")

    if self.runner_args.network_bytes_limit:
      if (self.runner_args.network_bytes_limit <
          self.context.network_bytes_sent):
        # We have exceeded our byte limit, stop this flow.
        raise FlowRunnerError("Network bytes limit exceeded.")
1114394
def get_cpu_info(self) -> str:
        ''''''
        output, _ = self._execute(
            '-s', self.device_sn, 'shell', 'cat', '/proc/cpuinfo')
        return output
828019
def cpu():
    '''
    
    '''

    # Test data
    max_primes = [500, 1000, 2500, 5000]

    # Initializing the test variables
    test_command = 'sysbench --test=cpu --cpu-max-prime={0} run'
    result = None
    ret_val = {}

    # Test beings!
    for primes in max_primes:
        key = 'Prime numbers limit: {0}'.format(primes)
        run_command = test_command.format(primes)
        result = __salt__['cmd.run'](run_command)
        ret_val[key] = _parser(result)

    return ret_val
567849
def get_docker_cpu(self, container_id, all_stats):
        
        cpu_new = {}
        ret = {'total': 0.0}

        # Read the stats
        # For each container, you will find a pseudo-file cpuacct.stat,
        # containing the CPU usage accumulated by the processes of the container.
        # Those times are expressed in ticks of 1/USER_HZ of a second.
        # On x86 systems, USER_HZ is 100.
        try:
            cpu_new['total'] = all_stats['cpu_stats']['cpu_usage']['total_usage']
            cpu_new['system'] = all_stats['cpu_stats']['system_cpu_usage']
            cpu_new['nb_core'] = len(all_stats['cpu_stats']['cpu_usage']['percpu_usage'] or [])
        except KeyError as e:
            # all_stats do not have CPU information
            logger.debug("docker plugin - Cannot grab CPU usage for container {} ({})".format(container_id, e))
            logger.debug(all_stats)
        else:
            # Previous CPU stats stored in the cpu_old variable
            if not hasattr(self, 'cpu_old'):
                # First call, we init the cpu_old variable
                self.cpu_old = {}
                try:
                    self.cpu_old[container_id] = cpu_new
                except (IOError, UnboundLocalError):
                    pass

            if container_id not in self.cpu_old:
                try:
                    self.cpu_old[container_id] = cpu_new
                except (IOError, UnboundLocalError):
                    pass
            else:
                #
                cpu_delta = float(cpu_new['total'] - self.cpu_old[container_id]['total'])
                system_delta = float(cpu_new['system'] - self.cpu_old[container_id]['system'])
                if cpu_delta > 0.0 and system_delta > 0.0:
                    ret['total'] = (cpu_delta / system_delta) * float(cpu_new['nb_core']) * 100

                # Save stats to compute next stats
                self.cpu_old[container_id] = cpu_new

        # Return the stats
        return ret
604069
def set_count_auto(self, count=None):
        
        count = count or self._section.vars.CPU_CORES

        self._set('workers', count)

        return self._section
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
599585
def get_cpu_info_json():
	'''
	
	'''

	import json

	output = None

	# If running under pyinstaller, run normally
	if getattr(sys, 'frozen', False):
		info = _get_cpu_info_internal()
		output = json.dumps(info)
		output = "{0}".format(output)
	# if not running under pyinstaller, run in another process.
	# This is done because multiprocesing has a design flaw that
	# causes non main programs to run multiple times on Windows.
	else:
		from subprocess import Popen, PIPE

		command = [sys.executable, __file__, '--json']
		p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
		output = p1.communicate()[0]

		if p1.returncode != 0:
			return "{}"

		if not IS_PY2:
			output = output.decode(encoding='UTF-8')

	return output