本文整理匯總了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)
示例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
示例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
}
示例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)
示例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()
示例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_()
示例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()
示例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))
示例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)
示例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
示例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))
示例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()
示例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())
示例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)))
示例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