Monitoring macOS and Windows System Resources with Python
This guide explains why and how to monitor CPU, memory, and disk I/O on macOS or Windows using Python's psutil, matplotlib, and numpy libraries, covering performance analysis, troubleshooting, capacity planning, automated alerts, and includes a complete example script that visualizes resource usage over time.
Monitoring system resources such as CPU, memory, and disk I/O on macOS or Windows helps with performance analysis, troubleshooting, capacity planning, automated operations, and overall health assessment.
Key objectives include identifying processes that consume excessive CPU, detecting memory leaks, planning expansions before resources run out, and triggering alerts or automated actions when thresholds are exceeded.
Installation
Run pip install psutil matplotlib numpy to install the required libraries.
Example code
import psutil
import matplotlib.pyplot as plt
import numpy as np
import time
# 监控CPU使用率
def monitor_cpu():
cpu_percent = psutil.cpu_percent(interval=1)
return cpu_percent
# 监控内存使用情况
def monitor_memory():
mem = psutil.virtual_memory()
return mem.total / (1024**2), mem.used / (1024**2)
# 监控磁盘I/O
def monitor_disk_io():
disk_io = psutil.disk_io_counters(perdisk=False)
return disk_io.read_bytes / (1024**2), disk_io.write_bytes / (1024**2) # 转换为MB
# 创建图表
def create_combined_graph(data_dict, labels, colors, title):
x = np.arange(len(data_dict[labels[0]]))
fig, ax1 = plt.subplots()
ax1.set_title(title)
ax1.set_xlabel('Seconds')
ax1.set_ylabel('CPU Usage (%)', color='tab:red')
ax1.plot(x, data_dict['CPU Usage (%)'], label='CPU Usage', color='tab:red')
ax1.tick_params(axis='y', labelcolor='tab:red')
ax2 = ax1.twinx()
ax2.set_ylabel('Memory Used (MB)', color='tab:blue')
ax2.plot(x, data_dict['Memory Used (MB)'], label='Memory Used', color='tab:blue')
ax2.tick_params(axis='y', labelcolor='tab:blue')
ax3 = ax1.twinx()
ax3.spines["right"].set_position(("axes", 1.2)) # 设置第三个Y轴的位置
make_patch_spines_invisible(ax3)
ax3.spines["right"].set_visible(True)
ax3.set_ylabel('Disk I/O (MB)', color='tab:green')
ax3.plot(x, data_dict['Disk Reads (MB)'], label='Disk Reads', color='tab:orange')
ax3.plot(x, data_dict['Disk Writes (MB)'], label='Disk Writes', color='tab:green')
ax3.tick_params(axis='y', labelcolor='tab:green')
# 添加磁盘最后读写数据到右上角
last_disk_read = data_dict['Disk Reads (MB)'][-1]
last_disk_write = data_dict['Disk Writes (MB)'][-1]
fig.text(0.95, 0.95, f'Disk Reads: {last_disk_read:.2f} MB\nDisk Writes: {last_disk_write:.2f} MB',
ha='right', va='top', fontsize=10, color='gray', transform=fig.transFigure)
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
h3, l3 = ax3.get_legend_handles_labels()
ax1.legend(h1+h2+h3, l1+l2+l3, loc='upper center')
plt.show()
# 辅助函数,用于隐藏多余的边框
def make_patch_spines_invisible(ax):
ax.set_frame_on(False)
ax.patch.set_visible(False)
for sp in ax.spines.values():
sp.set_visible(False)
# 主监控函数
def main_monitor_combined():
data_dict = {
'CPU Usage (%)': [],
'Memory Used (MB)': [],
'Disk Reads (MB)': [],
'Disk Writes (MB)': [],
}
for _ in range(10):
cpu_percent = monitor_cpu()
data_dict['CPU Usage (%)'].append(cpu_percent)
mem_total, mem_used = monitor_memory()
data_dict['Memory Used (MB)'].append(mem_used)
disk_reads_mb, disk_writes_mb = monitor_disk_io()
data_dict['Disk Reads (MB)'].append(disk_reads_mb)
data_dict['Disk Writes (MB)'].append(disk_writes_mb)
time.sleep(1)
create_combined_graph(data_dict, ['CPU Usage (%)', 'Memory Used (MB)', 'Disk Reads (MB)', 'Disk Writes (MB)'],
['tab:red', 'tab:blue', 'tab:orange', 'tab:green'], 'System Resource Usage Over Time')
if __name__ == "__main__":
main_monitor_combined()The script produces a combined graph showing CPU usage, memory consumption, and disk I/O over time, as illustrated by the sample Mac output images.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.