Run typeperf to get total CPU usage -- haven't figured out how to get it per process.
169518
function() {
        if (process.platform !== 'win32') {
            return;
        }

        this._cpuConsole = child_process.spawn('typeperf', ['\\Processor(_Total)\\% Processor Time']);
        this._cpuConsole.stdout.on('data', _.bind(function(stdout) {

            stdout = stdout.toString();
            if (stdout && stdout.indexOf(',') === 0) {
                var cpu = parseFloat(stdout.substr(2, stdout.length - 3));
                this._cpuFrame(cpu);
            }
        }, this));
    }
681384
def get_usage(self, program_name=None):
        """"""
        program_name = os.path.relpath(program_name or sys.argv[0] or 'Dummy',
                                       self.base_dir)
        commands = OrderedDict(self.gather_commands())
        options = gather_command_line_options()
        long_usage = format_usage(program_name, self.doc, commands, options)
        # internal usage is a workaround because docopt cannot handle spaces
        # in program names. So for parsing we use 'dummy' as the program name.
        # for printing help etc. we want to use the actual program name.
        internal_usage = format_usage('dummy', self.doc, commands, options)
        short_usage = printable_usage(long_usage)
        return short_usage, long_usage, internal_usage
328689
function top () { // NOTE: Replacing line above
  // if (!opts) opts = {}

  // const tick = opts.interval || 1000
  // const started = Date.now()
  // const interval = setInterval(perSecond, tick)
  // const win = [{ time: process.hrtime(), cpu: process.cpuUsage(), delay: 0 }, null, null, null]
  const win = [{ time: process.hrtime(), cpu: process.cpuUsage() }, null, null, null] // NOTE: Replacing line above
  // const loopSampler = eld()

  let sec = 1

  // interval.unref()

  return {
    // pid: process.pid,
    // command: process.argv.join(' '),
    // started,
    // time () {
    //   return Date.now() - started
    // },
    // delay () {
    //   const btm = oldest()
    //   const timeDelta = process.hrtime(win[btm].time)
    //   const ms = timeDelta[0] * 1e3 + Math.floor(timeDelta[1] / 1e6)
    //   return Math.floor((loopSampler.delay - win[btm].delay) / (ms / tick))
    // },
    cpu () {
      const btm = oldest()
      const cpuDelta = process.cpuUsage(win[btm].cpu)
      const timeDelta = process.hrtime(win[btm].time)
      const us = timeDelta[0] * 1e6 + timeDelta[1] / 1e3
      perSecond() // NOTE: Added to skip timer and update at each check
      return {
        time: us,
        percent: (cpuDelta.system + cpuDelta.user) / us,
        system: cpuDelta.system,
        user: cpuDelta.user
      }
    }
    // memory () {
    //   const mem = process.memoryUsage()
    //   const total = os.totalmem()
    //   return {
    //     percent: mem.rss / total,
    //     rss: mem.rss,
    //     total,
    //     heapPercent: mem.heapUsed / mem.heapTotal,
    //     heapUsed: mem.heapUsed,
    //     heapTotal: mem.heapTotal,
    //     external: mem.external
    //   }
    // },
    // loadavg () {
    //   return os.loadavg()
    // },
    // destroy () {
    //   clearInterval(interval)
    // },
    // toString () {
    //   const mem = this.memory()
    //   return `cpu: ${pct(this.cpu().percent)} | rss: ${p(mem.rss)} (${pct(mem.percent)}) | heap: ${p(mem.heapUsed)} / ${p(mem.heapTotal)} (${pct(mem.heapPercent)}) | ext: ${p(mem.external)} | delay: ${this.delay()} ms | ${time(this.time())} | loadavg: ${os.loadavg().map(fixed2).join(', ')}`
    // }
  }

  function oldest () {
    let btm = (sec - 4) & 3
    while (!win[btm]) btm = (btm + 1) & 3
    return btm
  }

  function perSecond () {
    const ptr = sec++ & 3
    // win[ptr] = { time: process.hrtime(), cpu: process.cpuUsage(), delay: loopSampler.delay }
    win[ptr] = { time: process.hrtime(), cpu: process.cpuUsage() } // NOTE: Replacing line above
  }
}
692575
def GetHostProcessorSpeed(self):
        ''''''
        counter = c_uint()
        ret = vmGuestLib.VMGuestLib_GetHostProcessorSpeed(self.handle.value, byref(counter))
        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
        return counter.value
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)()
1188098
def _orted_process():
    """"""
    for i in range(5 * 60):
        procs = [p for p in psutil.process_iter(attrs=['name']) if p.info['name'] == 'orted']

        if procs:
            return procs
        time.sleep(1)
80984
def get_cpu_status(self, cpu):
        
        if not isinstance(cpu, baseinteger):
            raise TypeError("cpu can only be an instance of type baseinteger")
        attached = self._call("getCPUStatus",
                     in_p=[cpu])
        return attached
235564
def getApplicationProcessId(self, pchAppKey):
        """"""

        fn = self.function_table.getApplicationProcessId
        result = fn(pchAppKey)
        return result
732339
function docker_calcCPUPercent(cpu_stats, precpu_stats) {
  /**
   * @namespace
   * @property {object}  cpu_usage
   * @property {number}  cpu_usage.total_usage
   * @property {number}  system_cpu_usage
   * @property {object}  cpu_usage
   * @property {Array}  cpu_usage.percpu_usage
   */

  if (!_windows) {
    let cpuPercent = 0.0;
    // calculate the change for the cpu usage of the container in between readings
    let cpuDelta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
    // calculate the change for the entire system between readings
    let systemDelta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage;

    if (systemDelta > 0.0 && cpuDelta > 0.0) {
      // calculate the change for the cpu usage of the container in between readings
      cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0;
    }

    return cpuPercent;
  } else {
    let nanoSecNow = util.nanoSeconds();
    let cpuPercent = 0.0;
    if (_docker_last_read > 0) {
      let possIntervals = (nanoSecNow - _docker_last_read); //  / 100 * os.cpus().length;
      let intervalsUsed = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
      if (possIntervals > 0) {
        cpuPercent = 100.0 * intervalsUsed / possIntervals;
      }
    }
    _docker_last_read = nanoSecNow;
    return cpuPercent;
  }
}
301988
@Override
	protected int detectTotalCpuPercent() throws Exception {
		Process process = null;
		try {

			// Execute command
			String cmd;
			if (command == null || command.isEmpty()) {
				String os = System.getProperty("os.name").toLowerCase();
				if (os.indexOf("win") >= 0) {

					// Windows command to query the actual CPU usage
					cmd = "wmic cpu get loadpercentage";

				} else {

					// Linux command to query the actual CPU usage
					cmd = "top -b -n2 -p 1 | fgrep \"Cpu(s)\" | tail -1 | awk -F'id,' -v prefix=\"$prefix\" "
							+ "'{ split($1, vs, \",\"); v=vs[length(vs)]; sub(\"%\", \"\", v); printf \"%s%.1f%%\n\", prefix, 100 - v }'";
				}
			} else {
				cmd = command;
			}
			process = Runtime.getRuntime().exec(cmd);
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			StringBuilder tmp = new StringBuilder();
			String line = "";
			while ((line = reader.readLine()) != null) {
				tmp.setLength(0);
				char[] chars = line.toCharArray();
				for (char c : chars) {
					if (Character.isDigit(c)) {
						tmp.append(c);
					}
					if (c == ',' || c == '.') {
						tmp.append('.');
					}
				}
				if (tmp.length() > 0) {
					try {
						return (int) Double.parseDouble(tmp.toString());
					} catch (Exception ignored) {
					}
				}
			}
		} finally {
			if (process != null) {
				try {
					process.destroy();
				} catch (Exception ignored) {
				}
			}
		}
		return 0;
	}
974935
def get_usage(self):
        
        usage = {}

        for cpu, timings in self.get_cpu_timings().items():
            cpu_total = sum(timings)
            del timings[3:5]
            cpu_busy = sum(timings)
            cpu_usage = self.calculate_usage(cpu, cpu_total, cpu_busy)

            usage['usage_' + cpu] = cpu_usage

        # for backward compatibility
        usage['usage'] = usage['usage_cpu']

        return usage
1176502
def get_build_output(self, process):
        

        while True:
            output = process.stdout.readline()
            if output == b'' and process.poll() is not None:
                if process.returncode > 0:
                    raise Exception("Compilation ended with an error"
                                    ".\nSTDERR\n%s\nSTDOUT\n%s" %
                                    (process.stderr.read(),
                                     process.stdout.read()))
                return
            if output:
                # Parse the output to get current and total tasks
                # This assumes the progress displayed by waf is in the form
                # [current/total]
                matches = re.search(r'\[\s*(\d+?)/(\d+)\].*',
                                    output.strip().decode('utf-8'))
                if matches is not None:
                    yield [int(matches.group(1)), int(matches.group(2))]
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
1097672
def _log_performance(self, perf_list):
        """"""
        # Compute overall performance numbers.
        totalProgramTime = sum(perf.program_time for perf in perf_list)
        program_byte_count = sum(perf.total_byte_count for perf in perf_list)
        actual_program_byte_count = sum(perf.program_byte_count for perf in perf_list)
        actual_program_page_count = sum(perf.program_page_count for perf in perf_list)
        skipped_byte_count = sum(perf.skipped_byte_count for perf in perf_list)
        skipped_page_count = sum(perf.skipped_page_count for perf in perf_list)
        
        # Compute kbps while avoiding a potential zero-div error.
        if totalProgramTime == 0:
            kbps = 0
        else:
            kbps = (program_byte_count/1024) / totalProgramTime
        
        if any(perf.program_type == FlashBuilder.FLASH_CHIP_ERASE for perf in perf_list):
            LOG.info("Erased chip, programmed %d bytes (%s), skipped %d bytes (%s) at %.02f kB/s",
                actual_program_byte_count, get_page_count(actual_program_page_count),
                skipped_byte_count, get_page_count(skipped_page_count),
                kbps)
        else:
            erase_byte_count = sum(perf.erase_byte_count for perf in perf_list)
            erase_sector_count = sum(perf.erase_sector_count for perf in perf_list)

            LOG.info("Erased %d bytes (%s), programmed %d bytes (%s), skipped %d bytes (%s) at %.02f kB/s", 
                erase_byte_count, get_sector_count(erase_sector_count),
                actual_program_byte_count, get_page_count(actual_program_page_count),
                skipped_byte_count, get_page_count(skipped_page_count),
                kbps)
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};
    }
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 {}
590123
def get_process_mapping():
    
    stat_name = detect_proc()
    self_tty = _get_stat(os.getpid(), stat_name)[0]
    processes = {}
    for pid in os.listdir('/proc'):
        if not pid.isdigit():
            continue
        try:
            tty, ppid = _get_stat(pid, stat_name)
            if tty != self_tty:
                continue
            args = _get_cmdline(pid)
            processes[pid] = Process(args=args, pid=pid, ppid=ppid)
        except IOError:
            # Process has disappeared - just ignore it.
            continue
    return processes