Python psutil.cpu_percent() Examples

The following are 30 code examples of psutil.cpu_percent(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module psutil , or try the search function .
Example #1
Source File: monitor.py    From indy-plenum with Apache License 2.0 7 votes vote down vote up
def captureSystemPerformance(self):
        logger.debug("{} capturing system performance".format(self))
        timestamp = time.time()
        cpu = psutil.cpu_percent(interval=None)
        ram = psutil.virtual_memory()
        curr_network = self.calculateTraffic()
        network = curr_network - self.lastKnownTraffic
        self.lastKnownTraffic = curr_network
        cpu_data = {
            'time': timestamp,
            'value': cpu
        }
        ram_data = {
            'time': timestamp,
            'value': ram.percent
        }
        traffic_data = {
            'time': timestamp,
            'value': network
        }
        return {
            'cpu': cpu_data,
            'ram': ram_data,
            'traffic': traffic_data
        } 
Example #2
Source File: resource_info_alert.py    From ahenk with GNU Lesser General Public License v3.0 7 votes vote down vote up
def gather_resource_usage(self, task_id):
        # Memory usage
        memory_usage = psutil.virtual_memory()
        self.logger.debug("Memory usage: {0}".format(memory_usage))
        # Disk usage
        disk_usage = psutil.disk_usage('/')
        self.logger.debug("Disk usage: {0}".format(disk_usage))
        # CPU usage
        cpu_percentage = psutil.cpu_percent(interval=1)
        self.logger.debug("CPU percentage: {0}".format(cpu_percentage))

        data = {'memoryUsage': str(memory_usage), 'diskUsage': str(disk_usage), 'cpuPercentage': str(cpu_percentage)}
        command = 'python3 /opt/ahenk/ahenkd.py send -t {0} -m {1} -s'.format(task_id, json.dumps(str(data)))
        result_code, p_out, p_err = self.execute(command)
        if result_code != 0:
            self.logger.error("Error occurred while sending message: " + str(p_err)) 
Example #3
Source File: utils.py    From mlens with MIT License 6 votes vote down vote up
def _recorder(pid, stop, ival):
    """Subprocess call function to record cpu and memory."""
    t = t0 = time()

    process = psutil.Process(pid)

    if stop is None:
        while True:
            m = process.memory_info()
            print(psutil.cpu_percent(), ',', m[0], ',', m[1])
            sleep(ival)
            t = time()
    else:
        while t - t0 < stop:
            m = process.memory_info()
            print(psutil.cpu_percent(), ',', m[0], ',', m[1])
            sleep(ival)
            t = time() 
Example #4
Source File: runcat.py    From Tools with MIT License 6 votes vote down vote up
def runcatCPU():
    app = QApplication(sys.argv)
    # 最后一个可视的窗口退出时程序不退出
    app.setQuitOnLastWindowClosed(False)
    icon = QSystemTrayIcon()
    icon.setIcon(QIcon('icons/0.png'))
    icon.setVisible(True)
    cpu_percent = psutil.cpu_percent(interval=1) / 100
    cpu_percent_update_fps = 20
    fps_count = 0
    while True:
        fps_count += 1
        if fps_count > cpu_percent_update_fps:
            cpu_percent = psutil.cpu_percent(interval=1) / 100
            fps_count = 0
        # 开口向上的抛物线, 左边递减
        time_interval = (cpu_percent * cpu_percent - 2 * cpu_percent + 2) / 20
        for i in range(5):
            icon.setIcon(QIcon('icons/%d.png' % i))
            icon.setToolTip('cpu: %.2f' % cpu_percent)
            time.sleep(time_interval)
    app.exec_() 
Example #5
Source File: exp_utils.py    From RegRCNN with Apache License 2.0 6 votes vote down vote up
def sysmetrics_update(self, global_step=None):
        if global_step is None:
            global_step = time.strftime("%x_%X")
        mem = psutil.virtual_memory()
        mem_used = (mem.total - mem.available)
        gpu_vals = self.gpu_logger.get_vals()
        rel_time = time.time() - self.sysmetrics_start_time
        self.sysmetrics.loc[len(self.sysmetrics)] = [global_step, rel_time,
                                                     psutil.cpu_percent(), mem_used / 1024 ** 3,
                                                     mem_used / mem.total * 100,
                                                     psutil.swap_memory().used / 1024 ** 3,
                                                     int(gpu_vals['gpu_graphics_util']),
                                                     *[torch.cuda.memory_allocated(d) / 1024 ** 3 for d in
                                                       range(torch.cuda.device_count())],
                                                     *[torch.cuda.memory_cached(d) / 1024 ** 3 for d in
                                                       range(torch.cuda.device_count())]
                                                     ]
        return self.sysmetrics.loc[len(self.sysmetrics) - 1].to_dict() 
Example #6
Source File: statusapi.py    From minemeld-core with Apache License 2.0 6 votes vote down vote up
def get_system_status():
    data_path = config.get('MINEMELD_LOCAL_PATH', None)
    if data_path is None:
        jsonify(error={'message': 'MINEMELD_LOCAL_PATH not set'}), 500

    res = {}
    res['cpu'] = psutil.cpu_percent(interval=1, percpu=True)
    res['memory'] = psutil.virtual_memory().percent
    res['swap'] = psutil.swap_memory().percent
    res['disk'] = psutil.disk_usage(data_path).percent
    res['sns'] = SNS_AVAILABLE

    return jsonify(result=res, timestamp=int(time.time() * 1000)) 
Example #7
Source File: top.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def poll(interval):
    # sleep some time
    time.sleep(interval)
    procs = []
    procs_status = {}
    for p in psutil.process_iter():
        try:
            p.dict = p.as_dict(['username', 'nice', 'memory_info',
                                'memory_percent', 'cpu_percent',
                                'cpu_times', 'name', 'status'])
            try:
                procs_status[p.dict['status']] += 1
            except KeyError:
                procs_status[p.dict['status']] = 1
        except psutil.NoSuchProcess:
            pass
        else:
            procs.append(p)

    # return processes sorted by CPU percent usage
    processes = sorted(procs, key=lambda p: p.dict['cpu_percent'],
                       reverse=True)
    return (processes, procs_status) 
Example #8
Source File: util_source.py    From s-tui with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
        if not hasattr(psutil, "cpu_percent"):
            self.is_available = False
            logging.debug("cpu utilization is not available from psutil")
            return

        Source.__init__(self)

        self.name = 'Util'
        self.measurement_unit = '%'
        self.pallet = ('util light', 'util dark',
                       'util light smooth', 'util dark smooth')

        self.last_measurement = [0] * (psutil.cpu_count() + 1)

        self.available_sensors = ['Avg']
        for core_id in range(psutil.cpu_count()):
            self.available_sensors.append("Core " + str(core_id)) 
Example #9
Source File: gui.py    From ffw with GNU General Public License v3.0 6 votes vote down vote up
def updateGui(screen, boxes, data):
    maxy, maxx = screen.getmaxyx()

    date = str(time.strftime("%c"))
    screen.addstr(1, maxx - len(date) - 2, date)

    screen.addstr(3, 15, '%3d' % (psutil.cpu_percent()))
    # svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304)
    screen.addstr(4, 15, str(psutil.virtual_memory()[4] / (1024 * 1024)))

    screen.refresh()
    n = 0
    for box in boxes:
        testspersecond = '%8d' % data[n]["testspersecond"]
        testcount = '%8d' % data[n]["testcount"]
        crashcount = '%8d' % data[n]["crashcount"]
        box.addstr(1, 1, testspersecond)
        box.addstr(2, 1, testcount)
        box.addstr(3, 1, crashcount)
        box.refresh()
        n += 1 
Example #10
Source File: statsd-agent.py    From dino with Apache License 2.0 6 votes vote down vote up
def cpu_times_percent():
    c = statsd.StatsClient(STATSD_HOST, 8125, prefix=PREFIX + 'system.cpu')
    while True:
        value = psutil.cpu_percent(interval=1)
        c.gauge('system_wide.percent', value)

        cpu_t_percent = psutil.cpu_times_percent(interval=1)
        c.gauge('system_wide.times_percent.user', cpu_t_percent.user)
        c.gauge('system_wide.times_percent.nice', cpu_t_percent.nice)
        c.gauge('system_wide.times_percent.system', cpu_t_percent.system)
        c.gauge('system_wide.times_percent.idle', cpu_t_percent.idle)
        c.gauge('system_wide.times_percent.iowait', cpu_t_percent.iowait)
        c.gauge('system_wide.times_percent.irq', cpu_t_percent.irq)
        c.gauge('system_wide.times_percent.softirq', cpu_t_percent.softirq)
        c.gauge('system_wide.times_percent.steal', cpu_t_percent.steal)
        c.gauge('system_wide.times_percent.guest', cpu_t_percent.guest)
        c.gauge('system_wide.times_percent.guest_nice', cpu_t_percent.guest_nice)
        time.sleep(GRANULARITY) 
Example #11
Source File: graph.py    From displayotron with MIT License 6 votes vote down vote up
def redraw(self, menu):
        now = self.millis()
        if now - self.last < 1000:
            return false

        self.cpu_samples.append(psutil.cpu_percent())
        self.cpu_samples.pop(0)
        self.cpu_avg = sum(self.cpu_samples) / len(self.cpu_samples)

        self.cpu_avg = round(self.cpu_avg * 100.0) / 100.0

        menu.write_row(0, 'CPU Load')
        menu.write_row(1, str(self.cpu_avg) + '%')
        menu.write_row(2, '#' * int(16 * (self.cpu_avg / 100.0)))

        if self.backlight is not None:
            self.backlight.set_graph(self.cpu_avg / 100.0) 
Example #12
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
def cpu_percent(self, per_cpu: bool = False, interval: Optional[float] = None) -> Union[float, List[float]]:
        """
        Get the CPU load percentage.

        :param per_cpu: Get per-CPU stats (default: False).
        :param interval: When *interval* is 0.0 or None compares system CPU times elapsed since last call or module
            import, returning immediately (non blocking). That means the first time this is called it will
            return a meaningless 0.0 value which you should ignore. In this case is recommended for accuracy that this
            function be called with at least 0.1 seconds between calls.
        :return: float if ``per_cpu=False``, ``list[float]`` otherwise.
        """
        import psutil
        percent = psutil.cpu_percent(percpu=per_cpu, interval=interval)

        if per_cpu:
            return [p for p in percent]
        return percent 
Example #13
Source File: resource_info_alert.py    From ahenk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def gather_resource_usage(self, task_id):
        # Memory usage
        memory_usage = psutil.virtual_memory()
        self.logger.debug("Memory usage: {0}".format(memory_usage))
        # Disk usage
        disk_usage = psutil.disk_usage('/')
        self.logger.debug("Disk usage: {0}".format(disk_usage))
        # CPU usage
        cpu_percentage = psutil.cpu_percent(interval=1)
        self.logger.debug("CPU percentage: {0}".format(cpu_percentage))

        data = {'memoryUsage': str(memory_usage), 'diskUsage': str(disk_usage), 'cpuPercentage': str(cpu_percentage)}
        command = 'python3 /opt/ahenk/ahenkd.py send -t {0} -m {1} -s'.format(task_id, json.dumps(str(data)))
        result_code, p_out, p_err = self.execute(command)
        if result_code != 0:
            self.logger.error("Error occurred while sending message: " + str(p_err)) 
Example #14
Source File: cpu.py    From bluebanquise with MIT License 5 votes vote down vote up
def collect(self):
        g = GaugeMetricFamily('system_cpu_load_percent', 'System CPU load in percent, from psutil')
        cpu_load = psutil.cpu_percent()
        print('CPU collector. cpu load: '+str(cpu_load))
        g.add_metric(['cpu_load'], cpu_load)
        yield g 
Example #15
Source File: script_ex.py    From heartbeats with MIT License 5 votes vote down vote up
def get_cpu_info():
    return {
        'percent': psutil.cpu_percent(interval=0),
        'count': psutil.cpu_count()
    } 
Example #16
Source File: cpu.py    From bluebanquise with MIT License 5 votes vote down vote up
def collect(self):
        g = GaugeMetricFamily('system_cpu_load_percent', 'System CPU load in percent, from psutil')
        cpu_load = psutil.cpu_percent()
        print('CPU collector. cpu load: '+str(cpu_load))
        g.add_metric(['cpu_load'], cpu_load)
        yield g 
Example #17
Source File: util_source.py    From s-tui with GNU General Public License v2.0 5 votes vote down vote up
def update(self):
        self.last_measurement = [psutil.cpu_percent(interval=0.0,
                                                    percpu=False)]
        for util in psutil.cpu_percent(interval=0.0, percpu=True):
            logging.info("Core id util %s", util)
            self.last_measurement.append(float(util))

        logging.info("Utilization recorded %s", self.last_measurement) 
Example #18
Source File: sysinfo.py    From sia-cog with MIT License 5 votes vote down vote up
def getCPUUsage():
    result = {"cpu_usage": psutil.cpu_percent(True),
              "mem_usage": psutil.virtual_memory().percent}

    return result 
Example #19
Source File: os_stats.py    From MCVirt with GNU General Public License v2.0 5 votes vote down vote up
def get_cpu_usage():
        """Obtain CPU usage statistics."""
        return cpu_percent() 
Example #20
Source File: cpu_utilization.py    From unicorn-remote with MIT License 5 votes vote down vote up
def update_indicators(self):
        for indicator, cpu_percent in zip(self.indicators, self.cpu_percents):
            indicator.update(cpu_percent / 100) 
Example #21
Source File: uiMainWindow.py    From TradeSim with Apache License 2.0 5 votes vote down vote up
def getCpuMemory(self):
        """获取CPU和内存状态信息"""
        cpuPercent = psutil.cpu_percent()
        memoryPercent = psutil.virtual_memory().percent
        return u'CPU使用率:%d%%   内存使用率:%d%%' % (cpuPercent, memoryPercent)
        
        # ---------------------------------------------------------------------- 
Example #22
Source File: system_sensors.py    From system_sensors with MIT License 5 votes vote down vote up
def get_cpu_usage():
    return str(psutil.cpu_percent(interval=None)) 
Example #23
Source File: baseDriver.py    From BioQueue with Apache License 2.0 5 votes vote down vote up
def get_cpu_percent():
    return psutil.cpu_percent(interval=1) 
Example #24
Source File: splitter_dbs_simulator.py    From simulator with GNU General Public License v3.0 5 votes vote down vote up
def get_cpu_usage(self):
        while True:
            self.cpu_usage = 0.1*psutil.cpu_percent() + 0.9*self.cpu_usage
            sys.stderr.write(f" {int(self.cpu_usage)}"); sys.stderr.flush()
            time.sleep(0.5) 
Example #25
Source File: system_diagnostics_logger.py    From universe with MIT License 5 votes vote down vote up
def run(self):
        while True:
            cpu_times, chrome_reset = self.cpu_times()
            print(json.dumps({
                'time': time.time(),
                'cpu_times': cpu_times,
                'cpu_percent': psutil.cpu_percent(percpu=True),
                'chrome_reset': chrome_reset,
            }), flush=True)
            self.chrome_reset = False
            time.sleep(self.interval) 
Example #26
Source File: resource_monitoring.py    From distributed_framework with Apache License 2.0 5 votes vote down vote up
def get_os_cpu_avaragecpu(self):
        result = psutil.cpu_percent(1, percpu=False)
        self.logger.debug(result)
        return result 
Example #27
Source File: script.py    From heartbeats with MIT License 5 votes vote down vote up
def get_process_infos():
    procs = []
    for p in psutil.process_iter():
        try:
            p.dict = p.as_dict(['username', 'nice', 'memory_info',
                                'memory_percent', 'cpu_percent',
                                'cpu_times', 'name', 'cmdline', 'status'])
        except psutil.NoSuchProcess:
            pass
        else:
            procs.append(p)

    # return processes sorted by CPU percent usage
    procs = sorted(procs, key=lambda p: p.dict['memory_percent'],
                   reverse=True)

    filer_cmdlines = [
        'nsshd: npaicbbuser@notty',
    ]

    process_infos = []
    for p in procs:
        cmdline = " ".join(p.dict['cmdline']).strip()
        if not cmdline:
            continue
        filter_flag = False
        for filer_cmdline in filer_cmdlines:
            if filer_cmdline in cmdline:
                filter_flag = True
                break
        if filter_flag:
            continue
        process_infos.append(cmdline.strip())

    return process_infos 
Example #28
Source File: script.py    From heartbeats with MIT License 5 votes vote down vote up
def get_cpu_info():
    return {
        'percent': psutil.cpu_percent(interval=0),
        'count': psutil.cpu_count()
    } 
Example #29
Source File: sensors.py    From indicator-sysmonitor with GNU General Public License v3.0 5 votes vote down vote up
def get_results(self):
            """Return a dict whose element are the sensors
            and their values"""
            res = {}
            from preferences import Preferences

            # We call this only once per update
            global cpu_load
            cpu_load = ps.cpu_percent(interval=0, percpu=True)

            # print (self.settings["custom_text"]) custom_text is the full visible string seen in Preferences edit field
            for sensor in Preferences.sensors_regex.findall(
                    self.settings["custom_text"]):

                sensor = sensor[1:-1]
                instance = self.get(sensor)

                if instance:
                    value = instance.get_value(sensor)
                    if value:
                        res[sensor] = value

                else:  # custom sensor
                    res[sensor] = BaseSensor.script_exec(self.settings["sensors"][sensor][1])

            return res 
Example #30
Source File: test_cisco.py    From Hands-On-Enterprise-Automation-with-Python with MIT License 5 votes vote down vote up
def animate(i):
    xar = []
    yar = []
    x = np.linspace(i, i + 1)
    y = psutil.cpu_percent(interval=1)
    xar.append(x)
    yar.append(y)
    plt.plot(xar, yar, 'ro')
    print xar
    print yar