在Linux中,我可以获得每个进程的内存使用量吗?我们使用sysstat/sar监控我们的服务器。但是,除了看到内存在某个时候从屋顶上掉下来之外,我们不能准确地指出哪个进程变得越来越大。有没有办法使用sar (或其他工具)来获取每个进程的内存使用情况?然后看看它,以后呢?
发布于 2019-12-05 02:29:03
sysstat包括pidstat,它的手册页上写着:
Linux pidstat命令用于监视当前由
内核管理的各个任务。它为使用选项
-p选择的每个任务或由Linux内核管理的每个任务写入标准输出活动……
Linux内核任务包括用户空间进程和线程(以及这里最不感兴趣的内核线程)。
但不幸的是,sysstat不支持从pidstat收集历史数据,而且作者似乎对提供这种支持不感兴趣(GitHub问题):
pidstat
也就是说,可以将pidstat的表格输出写入到文件中,然后对其进行解析。通常,感兴趣的是进程组,而不是系统上的每个进程。我将重点介绍一个进程及其子进程。
有什么可以作为例子呢?火狐。pgrep firefox返回其PID,$(pgrep -d, -P $(pgrep firefox))返回以逗号分隔的子代列表。鉴于此,pidstat命令可能如下所示:
LC_NUMERIC=C.UTF-8 watch pidstat -dru -hl \
-p '$(pgrep firefox),$(pgrep -d, -P $(pgrep firefox))' \
10 60 '>>' firefox-$(date +%s).pidstat一些观察结果:
LC_NUMERIC设置为使进程使用点作为十进制separator.watch,以便在进程子树changes.-d报告I/O统计信息的情况下每隔600秒重复一次pidstat,将-r设置为报告页面错误和内存利用率,将-u设置为pidstat,将所有报告组放在一行中,并使用-l显示进程命令名及其所有参数(好吧,因为它仍然会以127的速度对其进行修剪,所以使用characters).date来避免意外覆盖现有文件它会产生类似这样的结果:
Linux kernel version (host) 31/03/20 _x86_64_ (8 CPU)
# Time UID PID %usr %system %guest %CPU CPU minflt/s majflt/s VSZ RSS %MEM kB_rd/s kB_wr/s kB_ccwr/s iodelay Command
1585671289 1000 5173 0.50 0.30 0.00 0.80 5 0.70 0.00 3789880 509536 3.21 0.00 29.60 0.00 0 /usr/lib/firefox/firefox
1585671289 1000 5344 0.70 0.30 0.00 1.00 1 0.50 0.00 3914852 868596 5.48 0.00 0.00 0.00 0 /usr/lib/firefox/firefox -contentproc -childID 1 ...
1585671289 1000 5764 0.10 0.10 0.00 0.20 1 7.50 0.00 9374676 363984 2.29 0.00 0.00 0.00 0 /usr/lib/firefox/firefox -contentproc -childID 2 ...
1585671289 1000 5852 6.60 0.90 0.00 7.50 7 860.70 0.00 4276640 1040568 6.56 0.00 0.00 0.00 0 /usr/lib/firefox/firefox -contentproc -childID 3 ...
1585671289 1000 24556 0.00 0.00 0.00 0.00 7 0.00 0.00 419252 18520 0.12 0.00 0.00 0.00 0 /usr/lib/firefox/firefox -contentproc -parentBuildID ...
# Time UID PID %usr %system %guest %CPU CPU minflt/s majflt/s VSZ RSS %MEM kB_rd/s kB_wr/s kB_ccwr/s iodelay Command
1585671299 1000 5173 3.40 1.60 0.00 5.00 6 7.60 0.00 3789880 509768 3.21 0.00 20.00 0.00 0 /usr/lib/firefox/firefox
1585671299 1000 5344 5.70 1.30 0.00 7.00 6 410.10 0.00 3914852 869396 5.48 0.00 0.00 0.00 0 /usr/lib/firefox/firefox -contentproc -childID 1 ...
1585671299 1000 5764 0.00 0.00 0.00 0.00 3 0.00 0.00 9374676 363984 2.29 0.00 0.00 0.00 0 /usr/lib/firefox/firefox -contentproc -childID 2 ...
1585671299 1000 5852 1.00 0.30 0.00 1.30 1 90.20 0.00 4276640 1040452 6.56 0.00 0.00 0.00 0 /usr/lib/firefox/firefox -contentproc -childID 3 ...
1585671299 1000 24556 0.00 0.00 0.00 0.00 7 0.00 0.00 419252 18520 0.12 0.00 0.00 0.00 0 /usr/lib/firefox/firefox -contentproc -parentBuildID ...
...请注意,包含数据的每一行都以空格开头,因此解析很容易:
import pandas as pd
def read_columns(filename):
with open(filename) as f:
for l in f:
if l[0] != '#':
continue
else:
return l.strip('#').split()
else:
raise LookupError
def get_lines(filename, colnum):
with open(filename) as f:
for l in f:
if l[0] == ' ':
yield l.split(maxsplit=colnum - 1)
filename = '/path/to/firefox.pidstat'
columns = read_columns(filename)
exclude = 'CPU', 'UID',
df = pd.DataFrame.from_records(
get_lines(filename, len(columns)), columns=columns, exclude=exclude
)
numcols = df.columns.drop('Command')
df[numcols] = df[numcols].apply(pd.to_numeric, errors='coerce')
df['RSS'] = df.RSS / 1024 # Make MiB
df['Time'] = pd.to_datetime(df['Time'], unit='s', utc=True)
df = df.set_index('Time')
df.info()数据帧的结构如下:
Data columns (total 15 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 PID 6155 non-null int64
1 %usr 6155 non-null float64
2 %system 6155 non-null float64
3 %guest 6155 non-null float64
4 %CPU 6155 non-null float64
5 minflt/s 6155 non-null float64
6 majflt/s 6155 non-null float64
7 VSZ 6155 non-null int64
8 RSS 6155 non-null float64
9 %MEM 6155 non-null float64
10 kB_rd/s 6155 non-null float64
11 kB_wr/s 6155 non-null float64
12 kB_ccwr/s 6155 non-null float64
13 iodelay 6155 non-null int64
14 Command 6155 non-null object
dtypes: float64(11), int64(3), object(1)它可以以多种方式可视化,这取决于监控的重点是什么,但%CPU和RSS是最常见的指标。这里有一个例子。
import matplotlib.pyplot as plt
fig, axes = plt.subplots(len(df.PID.unique()), 2, figsize=(12, 8))
x_range = [df.index.min(), df.index.max()]
for i, pid in enumerate(df.PID.unique()):
subdf = df[df.PID == pid]
title = ', '.join([f'PID {pid}', str(subdf.index.max() - subdf.index.min())])
for j, col in enumerate(('%CPU', 'RSS')):
ax = subdf.plot(
y=col, title=title if j == 0 else None, ax=axes[i][j], sharex=True
)
ax.legend(loc='upper right')
ax.set_xlim(x_range)
plt.tight_layout()
plt.show()它会产生类似如下的图形:

发布于 2017-04-22 20:28:50
这是纯粹的偏好,但我会保持它的良好和简单,直到你知道你在寻找什么。我将创建一个cronjob,首先显示您的空闲内存、磁盘和cpu使用率,然后显示前十个罪魁祸首。
#!/bin/sh
free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }'
df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'
top -bn1 | grep load | awk '{printf "CPU Load: %.2f\n", $(NF-2)}'
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head在找到你的罪魁祸首之后,你可以更深入一点,深入研究一些细节。
https://stackoverflow.com/questions/43531543
复制相似问题