在CentOS系統上使用Python進行性能監控可以通過多種方法和工具來實現。以下是一些常用的方法和工具:
psutil
是一個跨平臺的Python庫,用于獲取系統資源使用情況,如CPU、內存、磁盤和網絡接口的流量等。
import psutil
# 獲取CPU使用率
cpu_percent = psutil.cpu_percent(interval=1)
print(f'CPU使用率: {cpu_percent}%')
# 獲取內存使用情況
memory = psutil.virtual_memory()
print(f'總內存: {memory.total / (1024**3):.2f}GB, 已用內存: {memory.used / (1024**3):.2f}GB, 內存使用百分比: {memory.percent}%')
# 獲取磁盤使用情況
disk_usage = psutil.disk_usage('/')
print(f'總空間: {disk_usage.total / (1024**3):.2f}GB, 已用空間: {disk_usage.used / (1024**3):.2f}GB, 可用空間: {disk_usage.free / (1024**3):.2f}GB')
# 獲取網絡接口流量
network_stats = psutil.net_io_counters()
print(f'發送字節數: {network_stats.bytes_sent / (1024**2):.2f}MB, 接收字節數: {network_stats.bytes_recv / (1024**2):.2f}MB')
Glances是一個基于Python的開源命令行監控工具,可以提供豐富的系統性能信息。
# 安裝EPEL倉庫
sudo yum -y install epel-release
# 安裝Glances
sudo yum -y install glances
# 啟動Glances以監控本地系統
glances
# 以Web界面方式啟動Glances
glances -w
可以通過Python腳本結合timeit
模塊來實現定時任務,并將監控數據存儲到文件中,便于后續分析。
import time
import psutil
import matplotlib.pyplot as plt
def plot_performance():
cpu_usage = []
memory_usage = []
while True:
cpu_percent = psutil.cpu_percent(interval=1)
memory_percent = psutil.virtual_memory().percent
cpu_usage.append(cpu_percent)
memory_usage.append(memory_percent)
plt.plot(cpu_usage, label='CPU Usage (%)')
plt.plot(memory_usage, label='Memory Usage (%)')
plt.xlabel('Time')
plt.ylabel('Usage (%)')
plt.legend()
plt.pause(1)
if __name__ == '__main__':
plot_performance()
PyMetrics
是一個專注于Python程序性能監控的庫,提供實時監控和數據可視化功能。
from pymetrics import MetricsRegistry, MetricsRenderer
from pymetrics.renderers import TextRenderer
registry = MetricsRegistry()
metrics = registry.register(
'cpu_usage', 'CPU usage', 'percent'
)
metrics.register(
'memory_usage', 'Memory usage', 'percent'
)
renderer = TextRenderer()
while True:
cpu_percent = psutil.cpu_percent(interval=1)
memory_percent = psutil.virtual_memory().percent
metrics.update({
'cpu_usage': cpu_percent,
'memory_usage': memory_percent
})
renderer.render(metrics)
time.sleep(1)
通過上述方法和工具,可以在CentOS系統上使用Python進行全面的性能監控,幫助管理員及時發現和解決系統性能問題。