本文目录导读:

PowerShell (Windows)
# 获取CPU使用率
Get-Counter "\Processor(_Total)\% Processor Time"
# 获取内存使用
Get-Counter "\Memory\Available MBytes"
# 获取磁盘IO
Get-Counter "\PhysicalDisk(_Total)\% Disk Time"
# 获取多个计数器
$counters = @(
"\Processor(_Total)\% Processor Time",
"\Memory\Available MBytes",
"\Network Interface(*)\Bytes Total/sec"
)
Get-Counter $counters
# 持续监控(每秒更新)
Get-Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 10
Python (跨平台)
# 方案1:使用psutil库
import psutil
import time
# CPU使用率
cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU: {cpu_percent}%")
# 内存信息
memory = psutil.virtual_memory()
print(f"Memory: {memory.percent}% used")
# 磁盘IO
disk_io = psutil.disk_io_counters()
print(f"Disk Read: {disk_io.read_bytes/1024/1024:.2f} MB")
# 网络IO
net_io = psutil.net_io_counters()
print(f"Network Sent: {net_io.bytes_sent/1024/1024:.2f} MB")
# 实时监控示例
def monitor_performance():
while True:
cpu = psutil.cpu_percent(interval=1)
mem = psutil.virtual_memory()
print(f"CPU: {cpu}% | Memory: {mem.percent}% | Available: {mem.available/1024/1024:.0f}MB")
time.sleep(1)
Bash (Linux)
#!/bin/bash
# CPU使用率
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
echo "CPU: $cpu_usage%"
# 内存使用
memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
echo "Memory: $memory_usage%"
# 磁盘使用
disk_usage=$(df -h / | awk 'NR==2 {print $5}')
echo "Disk: $disk_usage"
# 网络流量监控
interface="eth0"
rx_bytes=$(cat /sys/class/net/$interface/statistics/rx_bytes)
tx_bytes=$(cat /sys/class/net/$interface/statistics/tx_bytes)
echo "RX: $((rx_bytes/1024/1024)) MB | TX: $((tx_bytes/1024/1024)) MB"
Python + WMI (Windows特有)
import wmi
import pythoncom
def get_performance_counters():
pythoncom.CoInitialize()
c = wmi.WMI()
# CPU信息
for cpu in c.Win32_Processor():
print(f"CPU: {cpu.LoadPercentage}%")
# 内存信息
for os in c.Win32_OperatingSystem():
total_mem = int(os.TotalVisibleMemorySize) / 1024
free_mem = int(os.FreePhysicalMemory) / 1024
used_percent = ((total_mem - free_mem) / total_mem) * 100
print(f"Memory: {used_percent:.1f}%")
# 磁盘信息
for disk in c.Win32_LogicalDisk():
if disk.Size:
used_percent = ((int(disk.Size) - int(disk.FreeSpace)) / int(disk.Size)) * 100
print(f"Disk {disk.DeviceID}: {used_percent:.1f}%")
# 安装依赖:pip install wmi pywin32
完整监控脚本示例 (Python)
import psutil
import time
import csv
from datetime import datetime
class PerformanceMonitor:
def __init__(self):
self.metrics = []
def collect_metrics(self):
return {
'timestamp': datetime.now(),
'cpu_percent': psutil.cpu_percent(interval=1),
'memory_percent': psutil.virtual_memory().percent,
'memory_available_mb': psutil.virtual_memory().available / 1024 / 1024,
'disk_usage_percent': psutil.disk_usage('/').percent,
'network_bytes_sent': psutil.net_io_counters().bytes_sent,
'network_bytes_recv': psutil.net_io_counters().bytes_recv
}
def monitor(self, duration=60, interval=1):
"""监控指定时长"""
start_time = time.time()
while time.time() - start_time < duration:
metrics = self.collect_metrics()
self.metrics.append(metrics)
print(f"{metrics['timestamp']} - CPU: {metrics['cpu_percent']}% "
f"Mem: {metrics['memory_percent']}%")
time.sleep(interval)
def save_to_csv(self, filename='performance.csv'):
"""保存到CSV文件"""
if not self.metrics:
return
with open(filename, 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=self.metrics[0].keys())
writer.writeheader()
writer.writerows(self.metrics)
# 使用示例
monitor = PerformanceMonitor()
monitor.monitor(duration=10) # 监控10秒
monitor.save_to_csv()
安装依赖
# Python pip install psutil wmi pywin32 # PowerShell(Windows自带) # 无需安装 # Linux # 无需安装,使用系统命令
常用性能计数器
| 指标 | Windows计数器 | Linux命令 |
|---|---|---|
| CPU | \Processor\% Processor Time | top / mpstat |
| 内存 | \Memory\Available MBytes | free -m |
| 磁盘 | \PhysicalDisk\% Disk Time | iostat / df |
| 网络 | \Network Interface\Bytes Total/sec | iftop / nload |
| 进程 | \Process(*)\% Processor Time | ps aux |
选择哪种方法取决于你的操作系统和使用场景,PowerShell适合Windows环境,Python适合跨平台,Bash适合Linux服务器。