parses /proc/stat and calcualtes total and busy time
        (more specific USER_HZ see man 5 proc for further informations )
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
1080218
def stat( self, *args ):
        ''''''
        self.pipe.poll()
        if not self.pipe.returncode is None:
            '''cleanup handlers and timeouts'''
            if not self.expiration is None:
                self.ioloop.remove_timeout(self.expiration)
            for fd, dest in  self.streams:
                self.ioloop.remove_handler(fd)
            '''schedulle callback (first try to read all pending data)'''
            self.ioloop.add_callback(self.on_finish)
        for fd, dest in  self.streams:
            while True:
                try:
                    data = os.read(fd, 4096)
                    if len(data) == 0:
                        break
                    print(data.rstrip())
                except:
                    break
1252604
def stats_timing(stats_key, stats_logger):
    """"""
    start_ts = now_as_float()
    try:
        yield start_ts
    except Exception as e:
        raise e
    finally:
        stats_logger.timing(stats_key, now_as_float() - start_ts)
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}
25971
def gather_parsing_stats(self):
        """"""
        if self.verbose:
            start_time = time.clock()
            try:
                yield
            finally:
                elapsed_time = time.clock() - start_time
                printerr("Time while parsing:", elapsed_time, "seconds")
                if packrat_cache:
                    hits, misses = ParserElement.packrat_cache_stats
                    printerr("Packrat parsing stats:", hits, "hits;", misses, "misses")
        else:
            yield
1306520
def read_pid_stat(pid="self"):
    
    with open("/proc/%s/stat" % (pid,), "rb") as f:
        stat = f.readline().split()
    return {
        "utime": int(stat[13]),
        "stime": int(stat[14]),
        "cutime": int(stat[15]),
        "cstime": int(stat[16]),
    }
224266
def cpuinfo():
    """"""
    f = open("/proc/cpuinfo")
    hwinfo = {}
    for line in f.readlines():
        cpul = line.split(":")
        name = cpul[0].strip()
        if (len(cpul) > 1):
            val = cpul[1].strip()
        if (name == "model name"):
            hwinfo["CPU"] = val
        elif (name == "cpu MHz"):
            hwinfo["MHz"] = int(round(float(val)))
    f.close()
    return hwinfo
666300
def status(self):
        """"""
        if self.pidfile is None:
            raise DaemonError('Cannot get status of daemon without PID file')

        pid = self._read_pidfile()
        if pid is None:
            self._emit_message(
                '{prog} -- not running\n'.format(prog=self.prog))
            sys.exit(1)

        proc = psutil.Process(pid)
        # Default data
        data = {
            'prog': self.prog,
            'pid': pid,
            'status': proc.status(),
            'uptime': '0m',
            'cpu': 0.0,
            'memory': 0.0,
        }

        # Add up all the CPU and memory usage of all the
        # processes in the process group
        pgid = os.getpgid(pid)
        for gproc in psutil.process_iter():
            try:
                if os.getpgid(gproc.pid) == pgid and gproc.pid != 0:
                    data['cpu'] += gproc.cpu_percent(interval=0.1)
                    data['memory'] += gproc.memory_percent()
            except (psutil.Error, OSError):
                continue

        # Calculate the uptime and format it in a human-readable but
        # also machine-parsable format
        try:
            uptime_mins = int(round((time.time() - proc.create_time()) / 60))
            uptime_hours, uptime_mins = divmod(uptime_mins, 60)
            data['uptime'] = str(uptime_mins) + 'm'
            if uptime_hours:
                uptime_days, uptime_hours = divmod(uptime_hours, 24)
                data['uptime'] = str(uptime_hours) + 'h ' + data['uptime']
                if uptime_days:
                    data['uptime'] = str(uptime_days) + 'd ' + data['uptime']
        except psutil.Error:
            pass

        template = ('{prog} -- pid: {pid}, status: {status}, '
                    'uptime: {uptime}, %cpu: {cpu:.1f}, %mem: {memory:.1f}\n')
        self._emit_message(template.format(**data))
1132717
def print_total_timer():
    
    if len(_TOTAL_TIMER_DATA) == 0:
        return
    for k, v in six.iteritems(_TOTAL_TIMER_DATA):
        logger.info("Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time".format(
            k, v.sum, v.count, v.average))
1160405
private void calcChannelsStats(List<TaskRec> tasks) {
		for (ChannelWorkContext wc : channelContextMap.values()) {
			wc.lastGotCount = 0;
		}
		for (TaskRec taskRec : tasks) {
			ChannelWorkContext wc = channelContextMap.get(taskRec.channel);
			if (wc == null) {
				wc = new ChannelWorkContext(taskRec.channel);
				channelContextMap.put(taskRec.channel, wc);
			}
			wc.lastGotCount++;
		}
		// update next portion - double if found something, clear to minimum if not
		for (ChannelWorkContext wc : channelContextMap.values()) {
			if (wc.lastGotCount > 0) {
				wc.nextSlowLimit = Math.min(wc.nextSlowLimit * 2, MAX_TASK_COUNT);
				logger.debug("Channel " + wc.channelName + " nextSlowLimit=" + wc.nextSlowLimit);
			} else {
				wc.dropNextSlowLimit();
			}
		}
	}
966828
def timing(self, stat, time, sample_rate=1):
        
        stats = {stat: "%f|ms" % time}
        self.send(stats, sample_rate)
1315362
def get_time_eta(total_done, total, start_time):
    
    time_done = int(time()) - start_time
    speed = total_done / time_done

    if time_done > 0 and speed > 0:
        total_to_go = total - total_done
        time_to_go = total_to_go / speed
        minutes, seconds = divmod(time_to_go, 60)
        hours, minutes = divmod(minutes, 60)
        percentage = total_done * 100.0 / total
    else:
        percentage = 0
        hours = 0
        minutes = 0
        seconds = 0

    return {
        "done": int(total_done),
        "tot": int(total),
        "%": float("{0:.2f}".format(percentage)),
        "h": int(hours),
        "m": int(minutes),
        "s": int(seconds)
    }
1238757
def update_local(self):
        """"""
        # Grab CPU stats using psutil's cpu_percent and cpu_times_percent
        # Get all possible values for CPU stats: user, system, idle,
        # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+)
        # The following stats are returned by the API but not displayed in the UI:
        # softirq (Linux), guest (Linux 2.6.24+), guest_nice (Linux 3.2.0+)

        # Init new stats
        stats = self.get_init_value()

        stats['total'] = cpu_percent.get()
        cpu_times_percent = psutil.cpu_times_percent(interval=0.0)
        for stat in ['user', 'system', 'idle', 'nice', 'iowait',
                     'irq', 'softirq', 'steal', 'guest', 'guest_nice']:
            if hasattr(cpu_times_percent, stat):
                stats[stat] = getattr(cpu_times_percent, stat)

        # Additional CPU stats (number of events not as a %; psutil>=4.1.0)
        # ctx_switches: number of context switches (voluntary + involuntary) per second
        # interrupts: number of interrupts per second
        # soft_interrupts: number of software interrupts per second. Always set to 0 on Windows and SunOS.
        # syscalls: number of system calls since boot. Always set to 0 on Linux.
        cpu_stats = psutil.cpu_stats()
        # By storing time data we enable Rx/s and Tx/s calculations in the
        # XML/RPC API, which would otherwise be overly difficult work
        # for users of the API
        time_since_update = getTimeSinceLastUpdate('cpu')

        # Previous CPU stats are stored in the cpu_stats_old variable
        if not hasattr(self, 'cpu_stats_old'):
            # First call, we init the cpu_stats_old var
            self.cpu_stats_old = cpu_stats
        else:
            for stat in cpu_stats._fields:
                if getattr(cpu_stats, stat) is not None:
                    stats[stat] = getattr(cpu_stats, stat) - getattr(self.cpu_stats_old, stat)

            stats['time_since_update'] = time_since_update

            # Core number is needed to compute the CTX switch limit
            stats['cpucore'] = self.nb_log_core

            # Save stats to compute next step
            self.cpu_stats_old = cpu_stats

        return stats
1189678
def _print_stats(cls, stats: Statistics, human_format_speed: bool=True):
        ''''''
        time_length = datetime.timedelta(
            seconds=int(stats.stop_time - stats.start_time)
        )
        file_size = wpull.string.format_size(stats.size)

        if stats.bandwidth_meter.num_samples:
            speed = stats.bandwidth_meter.speed()

            if human_format_speed:
                speed_size_str = wpull.string.format_size(speed)
            else:
                speed_size_str = '{:.1f} b'.format(speed * 8)
        else:
            speed_size_str = _('-- B')

        _logger.info(_('FINISHED.'))
        _logger.info(__(
            _(
                'Duration: {preformatted_timedelta}. '
                'Speed: {preformatted_speed_size}/s.'
            ),
            preformatted_timedelta=time_length,
            preformatted_speed_size=speed_size_str,
        ))
        _logger.info(__(
            gettext.ngettext(
                'Downloaded: {num_files} file, {preformatted_file_size}.',
                'Downloaded: {num_files} files, {preformatted_file_size}.',
                stats.files
            ),
            num_files=stats.files,
            preformatted_file_size=file_size
        ))

        if stats.is_quota_exceeded:
            _logger.info(_('Download quota exceeded.'))
130781
public function getProcessStats()
    {

        // Time?
        if (!empty($this->settings['timer'])) {
            $t = new Timer('Process Stats');
        }

        // We'll return this after stuffing it with useful info
        $result = array(
            'exists' => true,
            'totals' => array(
                'running' => 0,
                'zombie' => 0,
                'sleeping' => 0,
                'stopped' => 0,
                'idle' => 0,
            ),
            'proc_total' => 0,
            'threads' => false, // I'm not sure how to get this
        );

        // Use ps
        try {
            // Get it
            $ps = $this->exec->exec('ps', 'ax');

            // Match them
            preg_match_all('/^\s*\d+\s+[\w?]+\s+([A-Z])\S*\s+.+$/m', $ps, $processes, PREG_SET_ORDER);

            // Get total
            $result['proc_total'] = count($processes);

            // Go through
            foreach ($processes as $process) {
                switch ($process[1]) {
                    case 'S':
                    case 'I':
                        $result['totals']['sleeping']++;
                    break;
                    case 'Z':
                        $result['totals']['zombie']++;
                    break;
                    case 'R':
                    case 'D':
                        $result['totals']['running']++;
                    break;
                    case 'T':
                        $result['totals']['stopped']++;
                    break;
                    case 'W':
                        $result['totals']['idle']++;
                    break;
                }
            }
        } catch (Exception $e) {
            Errors::add('Linfo Core', 'Error using `ps` to get process info');
        }

        // Give
        return $result;
    }
575714
def execution_time(object):
    

    @functools.wraps(object)
    def execution_time_wrapper(*args, **kwargs):
        """
        Implements execution timing.

        :param \*args: Arguments.
        :type \*args: \*
        :param \*\*kwargs: Keywords arguments.
        :type \*\*kwargs: \*\*
        :return: Object.
        :rtype: object
        """

        start_time = time.time()

        value = object(*args, **kwargs)

        end_time = time.time()

        sys.stdout.write("{0} | '{1}' object processed during '{2:f}' ms!\n".format(__name__,
                                                                                    object.__name__,
                                                                                    (end_time - start_time) * 1000.0))

        return value

    return execution_time_wrapper
597182
function get_cpu_idle() {
  var idle = 0;
  var cpus = os.cpus();
  var i, len;
  for (i=0, len = cpus.length; i < len; i += 1) {
    var cpu = cpus[i];
    var total = cpu.times.sys + cpu.times.idle + cpu.times.user + cpu.times.nice + cpu.times.irq;
    idle += (cpu.times.idle/total*100);
  }
  idle = idle / cpus.length;
  return idle;
}