以下是使用sigar库获取进程的 CPU 和内存使用率的示例代码:
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Who5;
import org.hyperic.sigar.Who5.Cpu;
import org.hyperic.sigar.Who5.Info;
import java.util.ArrayList;
import java.util.List;
public class ProcessMonitorWithSigar {
public static void main(String[] args) {
Sigar sigar = new Sigar();
try {
// 获取所有进程信息
Who5[] who5s = sigar.getWho5Array();
List<ProcessInfo> processInfos = new ArrayList<>();
for (Who5 who5 : who5s) {
Info info = who5.getInfo();
String processName = info.getName();
int pid = info.getPid();
// 获取 CPU 使用率
CpuPerc cpuPerc = sigar.getProcCpu(pid).getPercent();
// 获取内存使用量
long memoryUsage = sigar.getProcMem(pid).getResident();
// 假设总物理内存为 8GB(8589934592 字节),计算内存使用率
double totalMemory = 8589934592.0;
double memoryUsagePercent = memoryUsage / totalMemory * 100;
processInfos.add(new ProcessInfo(processName, pid, cpuPerc.getCombined(), memoryUsagePercent));
}
// 输出进程信息
for (ProcessInfo processInfo : processInfos) {
System.out.println("进程名称: " + processInfo.processName + ", PID: " + processInfo.pid + ", CPU 使用率: " + processInfo.cpuUsage + "%, 内存使用率: " + processInfo.memoryUsagePercent + "%");
}
} catch (SigarException e) {
e.printStackTrace();
}
}
static class ProcessInfo {
String processName;
int pid;
double cpuUsage;
double memoryUsagePercent;
public ProcessInfo(String processName, int pid, double cpuUsage, double memoryUsagePercent) {
this.processName = processName;
this.pid = pid;
this.cpuUsage = cpuUsage;
this.memoryUsagePercent = memoryUsagePercent;
}
}
}
请注意,上述代码中的总物理内存假设为 8GB,在实际应用中你需要根据系统实际情况获取总内存量,以更准确地计算内存使用率。同时,使用sigar库可能需要确保其与你的系统架构和 Java 版本兼容。