温馨提示×

cpustat输出数据在Debian上的可视化

小樊
42
2025-03-20 18:59:08
栏目: 智能运维
Debian服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

cpustat 是一个用于显示 CPU 统计信息的工具,它是 sysstat 包的一部分

首先,确保已经安装了 sysstat 包。在 Debian 上,可以使用以下命令安装:

sudo apt-get update
sudo apt-get install sysstat

接下来,使用 cpustat 收集 CPU 统计数据。例如,要收集 5 秒钟的数据并每隔 1 秒输出一次,可以运行:

sudo cpustat -u 1 5

这将输出类似以下内容:

Linux 5.4.0-42-generic (your-hostname) 	05/19/2021 	_x86_64_	(4 CPU)

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           12.34    0.01    3.45    0.78    0.00   83.42
           10.23    0.01    2.89    0.67    0.00   86.20
            9.87    0.02    3.12    0.81    0.00   86.78
           11.56    0.01    3.67    0.75    0.00   84.01

要将这些数据可视化,可以使用 Python 的 matplotlib 库。首先,确保已经安装了 matplotlib

pip install matplotlib

然后,创建一个名为 cpustat_visualization.py 的 Python 脚本,并添加以下代码:

import sys
import matplotlib.pyplot as plt
from collections import defaultdict

data = defaultdict(list)

for line in sys.stdin:
    if line.startswith("avg-cpu:"):
        continue
    fields = line.split()
    if len(fields) < 7:
        continue
    cpu_usage = fields[:7]
    for i, field in enumerate(cpu_usage):
        data[i].append(float(field))

fig, axs = plt.subplots(2, 4, figsize=(16, 8))

for i, ax in enumerate(axs.flatten()):
    if i < len(data):
        ax.plot(data[i], label=f"CPU {i}")
        ax.set_xlabel("Time")
        ax.set_ylabel("Usage (%)")
        ax.legend()

plt.tight_layout()
plt.show()

最后,运行以下命令将 cpustat 的输出传递给 Python 脚本:

sudo cpustat -u 1 5 | python cpustat_visualization.py

这将显示一个包含 CPU 使用率、nice 值、系统使用率、I/O 等待时间、偷取时间和空闲时间的图表。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:PyTorch在Debian上的数据可视化如何操作

0