当前位置: 首页>>代码示例>>Python>>正文


Python psutil.cpu_percent方法代码示例

本文整理汇总了Python中psutil.cpu_percent方法的典型用法代码示例。如果您正苦于以下问题:Python psutil.cpu_percent方法的具体用法?Python psutil.cpu_percent怎么用?Python psutil.cpu_percent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在psutil的用法示例。


在下文中一共展示了psutil.cpu_percent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: cpu_times_percent

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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) 
开发者ID:thenetcircle,项目名称:dino,代码行数:20,代码来源:statsd-agent.py

示例2: updateGui

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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 
开发者ID:dobin,项目名称:ffw,代码行数:23,代码来源:gui.py

示例3: captureSystemPerformance

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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
        } 
开发者ID:hyperledger,项目名称:indy-plenum,代码行数:27,代码来源:monitor.py

示例4: poll

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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) 
开发者ID:giampaolo,项目名称:psutil,代码行数:25,代码来源:top.py

示例5: _recorder

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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() 
开发者ID:flennerhag,项目名称:mlens,代码行数:20,代码来源:utils.py

示例6: runcatCPU

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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_() 
开发者ID:CharlesPikachu,项目名称:Tools,代码行数:24,代码来源:runcat.py

示例7: sysmetrics_update

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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() 
开发者ID:MIC-DKFZ,项目名称:RegRCNN,代码行数:20,代码来源:exp_utils.py

示例8: __init__

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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)) 
开发者ID:amanusk,项目名称:s-tui,代码行数:20,代码来源:util_source.py

示例9: redraw

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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) 
开发者ID:pimoroni,项目名称:displayotron,代码行数:19,代码来源:graph.py

示例10: cpu_percent

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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 
开发者ID:BlackLight,项目名称:platypush,代码行数:19,代码来源:__init__.py

示例11: gather_resource_usage

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
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)) 
开发者ID:Pardus-LiderAhenk,项目名称:ahenk,代码行数:18,代码来源:resource_info_alert.py

示例12: update

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
def update(self):
        self.data['cpu_percent'] = psutil.cpu_percent()
        self.data['cpu_percents'] = psutil.cpu_percent(percpu=True)
        self.data['memory'] = self._virtual_memory()
        self.data['swap'] = self._swap_memory()
        self.data['uptime'] = int(time.time() - self.data['boot_time'])
        super(Plugin, self).update() 
开发者ID:pkkid,项目名称:pkmeter,代码行数:9,代码来源:system.py

示例13: step

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
def step(self, amt=1):
        self.internal_delay = 0.5
        self.layout.all_off()
        usage = psutil.cpu_percent()
        self._usage.append(int(usage // 100.0 * self.height))

        for x in range(self.width):
            if self._usage[x] > 0:
                self.layout.drawLine(x, self.height,
                                     x, self.height - 1 - self._usage[x],
                                     self.palette()) 
开发者ID:ManiacalLabs,项目名称:BiblioPixelAnimations,代码行数:13,代码来源:CPUUsage.py

示例14: refreshCpuLoad

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
def refreshCpuLoad(self):
        self.cpu_load = list(map(int, psutil.cpu_percent(percpu=True))) 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:4,代码来源:system_status.py

示例15: get_process_usage_cpu

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import cpu_percent [as 别名]
def get_process_usage_cpu(self):
        """
        Get the used cpu power of this process

        :return: int
        """
        cpu = psutil.cpu_percent(interval=None)
        return cpu 
开发者ID:oliver-zehentleitner,项目名称:unicorn-binance-websocket-api,代码行数:10,代码来源:unicorn_binance_websocket_api_manager.py


注:本文中的psutil.cpu_percent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。