Start collecting cpu stats for the threads.
486903
public synchronized void start() {
    if (!running) {
      running = true;
      Thread t = new Thread(new CpuStatRunnable(), "ThreadCpuStatsCollector");
      t.setDaemon(true);
      t.start();
    }
  }
1036498
def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        if self.input_method == 'local':
            # Update stats using the standard system lib
            # Here, update is call for processcount AND processlist
            glances_processes.update()

            # Return the processes count
            stats = glances_processes.getcount()
        elif self.input_method == 'snmp':
            # Update stats using SNMP
            # Not avalaible
            pass

        # Update the stats
        self.stats = stats

        return self.stats
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));
    }
824490
def gather_data(registry):
    """"""

    # Get the host name of the machine
    host = socket.gethostname()

    # Create our collectors
    ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.",
                       {'host': host})
    cpu_metric = Gauge("cpu_usage_percent", "CPU usage percent.",
                       {'host': host})

    # register the metric collectors
    registry.register(ram_metric)
    registry.register(cpu_metric)

    # Start gathering metrics every second
    while True:
        time.sleep(1)

        # Add ram metrics
        ram = psutil.virtual_memory()
        swap = psutil.swap_memory()

        ram_metric.set({'type': "virtual", }, ram.used)
        ram_metric.set({'type': "virtual", 'status': "cached"}, ram.cached)
        ram_metric.set({'type': "swap"}, swap.used)

        # Add cpu metrics
        for c, p in enumerate(psutil.cpu_percent(interval=1, percpu=True)):
            cpu_metric.set({'core': c}, p)
390956
def start(self):
        """"""
        assert not self.interrupted
        for thread in self.worker_threads:
            thread.start()
        WorkerThread.start(self)
1238050
def process_build_metrics(context, build_processors):
    """"""
    build_metrics = OrderedDict()

    # reset all processors
    for p in build_processors:
        p.reset()

    # collect metrics from all processors
    for p in build_processors:
        build_metrics.update(p.build_metrics)

    return build_metrics
94483
function Cpu(kernel, number) {
    if (kernel === undefined || number === undefined)
      throw new Error('Missing arguments');
    this.kernel = kernel;
    this.cpuNumber = number;
    this.slices = [];
    this.counters = {};
    this.bounds = new tr.b.Range();
    this.samples_ = undefined; // Set during createSubSlices

    // Start timestamp of the last active thread.
    this.lastActiveTimestamp_ = undefined;

    // Identifier of the last active thread. On Linux, it's a pid while on
    // Windows it's a thread id.
    this.lastActiveThread_ = undefined;

    // Name and arguments of the last active thread.
    this.lastActiveName_ = undefined;
    this.lastActiveArgs_ = undefined;
  }
1277771
private void updateStats() {
    final ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    if (bean.isThreadCpuTimeEnabled()) {
      // Update stats for all current threads
      final long[] ids = bean.getAllThreadIds();
      Arrays.sort(ids);
      long totalCpuTime = 0L;
      for (long id : ids) {
        long cpuTime = bean.getThreadCpuTime(id);
        if (cpuTime != -1) {
          totalCpuTime += cpuTime;
          CpuUsage usage = threadCpuUsages.get(id);
          if (usage == null) {
            final ThreadInfo info = bean.getThreadInfo(id);
            usage = new CpuUsage(id, info.getThreadName());
            threadCpuUsages.put(id, usage);
          }
          usage.update(cpuTime);
        }
      }

      // Update jvm cpu usage, if possible we query the operating system mxbean so we get
      // an accurate total including any threads that may have been started and stopped
      // between sampling. As a fallback we use the sum of the cpu time for all threads found
      // in this interval.
      //
      // Total cpu time can be found in:
      // http://docs.oracle.com/javase/7/docs/jre/api/management/extension/\
      // com/sun/management/OperatingSystemMXBean.html
      //
      // We use reflection to avoid direct dependency on com.sun.* classes.
      final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
      try {
        final Method m = osBean.getClass().getMethod("getProcessCpuTime");
        final long jvmCpuTime = (Long) m.invoke(osBean);
        jvmCpuUsage.update((jvmCpuTime < 0) ? totalCpuTime : jvmCpuTime);
      } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        jvmCpuUsage.update(totalCpuTime);
      }

      // Handle ids in the map that no longer exist:
      // * Remove old entries if the last update time is over AGE_LIMIT
      // * Otherwise, update usage so rolling window is correct
      final long now = System.currentTimeMillis();
      final Iterator<Map.Entry<Long, CpuUsage>> iter = threadCpuUsages.entrySet().iterator();
      while (iter.hasNext()) {
        final Map.Entry<Long, CpuUsage> entry = iter.next();
        final long id = entry.getKey();
        final CpuUsage usage = entry.getValue();
        if (now - usage.getLastUpdateTime() > AGE_LIMIT) {
          iter.remove();
        } else if (Arrays.binarySearch(ids, id) < 0) {
          usage.updateNoValue();
        }
      }
    } else {
      LOGGER.debug("ThreadMXBean.isThreadCpuTimeEnabled() == false, cannot collect stats");
    }
  }
550267
def _init_threads(self):
        """"""
        if self._io_thread is None:
            self._io_thread = Thread(target=self._select)
            self._io_thread.start()

        if self._writer_thread is None:
            self._writer_thread = Thread(target=self._writer)
            self._writer_thread.start()
78270
def read_stat():
    
    data = []
    with open("/proc/stat", "rb") as stat_file:
        for line in stat_file:
            cpu_stat = line.split()
            if cpu_stat[0][:3] != b"cpu":
                break
            # First cpu line is aggregation of following lines, skip it
            if len(cpu_stat[0]) == 3:
                continue
            data.append(
                {
                    "times": {
                        "user": int(cpu_stat[1]),
                        "nice": int(cpu_stat[2]),
                        "sys": int(cpu_stat[3]),
                        "idle": int(cpu_stat[4]),
                        "irq": int(cpu_stat[6]),
                    }
                }
            )
    return data
295847
def run_benchmark(monitor):
    '''
    '''
    url = urlparse(monitor.cfg.test_url)
    name = slugify(url.path) or 'home'
    name = '%s_%d.csv' % (name, monitor.cfg.workers)
    monitor.logger.info('WRITING RESULTS ON "%s"', name)
    total = REQUESTS//monitor.cfg.workers

    with open(name, 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=FIELDNAMES)
        writer.writeheader()
        for pool_size in POOL_SIZES:
            size = pool_size//monitor.cfg.workers
            if size*monitor.cfg.workers != pool_size:
                monitor.logger.error('Adjust workes so that pool sizes '
                                     'can be evenly shared across them')
                monitor._loop.stop()

            # WORMUP
            requests = [monitor.send(worker, 'run', wormup, size, total) for
                        worker in monitor.managed_actors]
            yield from wait(requests)

            # BENCHMARK
            requests = [monitor.send(worker, 'run', bench) for
                        worker in monitor.managed_actors]
            results, pending = yield from wait(requests)
            assert not pending, 'Pending requets!'
            results = [r.result() for r in results]

            summary = {'concurrency': pool_size}
            for name in results[0]:
                summary[name] = reduce(add(name), results, 0)
            writer.writerow(summary)

            persec = summary['requests']/summary['time']
            monitor.logger.info('%d concurrency - %d requests - '
                                '%d errors - %.3f seconds - '
                                '%.2f requests/sec',
                                pool_size,
                                summary['requests'],
                                summary['errors'],
                                summary['time'],
                                persec)
166228
def run(self):
        """"""
        self.logger.info("Running with Python %s", sys.version.replace("\n", ""))
        self.logger.info("Running on platform %s", platform.platform())
        self.logger.info("Current cpu count is %d", multiprocessing.cpu_count())

        configuration = self.load_configuration()
        paths = [os.path.abspath(path) for path in Adapter(self.options).path]
        supported_extension = [
            ext.strip() for entry in configuration for ext in Adapter(entry).extension.split()]

        for path, path_and_filename, extension in Application.walk_files_for(paths, supported_extension):
            entry = Select(*configuration) \
                .where(lambda entry: extension in Adapter(entry).extension.split()) \
                .transform(lambda entry: Adapter(entry)) \
                .build()[0]
            # parsing file with regex to get loc and com values
            # 100 lines of code (total) with 50 lines of comments means: loc=50, com=50
            # the ratio would be then: 1.0
            loc, com = self.analyse(path_and_filename, entry.regex)
            ratio = float(com) / float(loc) if loc > 0 and com < loc else 1.0

            self.results.append({
                'type': entry.type,
                'file': path_and_filename.replace(path + '/', ''),
                'loc': loc,
                'com': com,
                'ratio': "%.2f" % ratio
            })
        # for the table we are mainly interested in ratio below defined threshold
        # (except you want to see all of your code: --show-all)
        ppresults = Select(*self.results).where(
            lambda entry: float(Adapter(entry).ratio) < Adapter(self.options).threshold or
            Adapter(self.options).show_all).build()

        # print out results in table format
        pprint(ppresults, keys=['ratio', 'loc', 'com', 'file', 'type'])

        if Adapter(self.options).average:
            all_ratio = Select(*self.results).transform(lambda entry: float(Adapter(entry).ratio)).build()
            avg_ratio = float(sum(all_ratio)) / float(len(all_ratio)) if len(all_ratio) > 0 else 1.0
            self.logger.info('average ratio is %.2f for %d files', avg_ratio, len(all_ratio))
            return avg_ratio >= Adapter(self.options).threshold

        # providing results (mainly for unittesting)
        return len(Select(*self.results).where(
            lambda entry: float(Adapter(entry).ratio) < Adapter(self.options).threshold).build()) == 0
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)()
390559
def start(self):
        """"""
        for i in range(self.min):
            self._threads.append(WorkerThread(self.server))
        for worker in self._threads:
            worker.setName("CP Server " + worker.getName())
            worker.start()
        for worker in self._threads:
            while not worker.ready:
                time.sleep(.1)
1161955
def run(self):
        
        for p in self._stats:
            # End of the thread has been asked
            if self.stopped():
                break
            # Scan a port (ICMP or TCP)
            if 'port' in p:
                self._port_scan(p)
                # Had to wait between two scans
                # If not, result are not ok
                time.sleep(1)
            # Scan an URL
            elif 'url' in p and requests_tag:
                self._web_scan(p)
744073
private void init() {
        assertUnlocked();
        
        lock.lock();
        try {
            httpSender.init(cfg);

            LOG.info(
                "Starting with "
                    + DEFAULT_REQ_PROC_COUNT + " request processors");

            procThreads = new RequestProcessor[DEFAULT_REQ_PROC_COUNT];

            for (int i = 0; i < procThreads.length; i++) {
                procThreads[i] = new RequestProcessor(i);
                procThreads[i].start();
            }

        } finally {
            lock.unlock();
        }
    }
540283
def cpu_count() -> int:
    """"""
    if multiprocessing is None:
        return 1
    try:
        return multiprocessing.cpu_count()
    except NotImplementedError:
        pass
    try:
        return os.sysconf("SC_NPROCESSORS_CONF")
    except (AttributeError, ValueError):
        pass
    gen_log.error("Could not detect number of processors; assuming 1")
    return 1