70 lines
2.3 KiB
Java
70 lines
2.3 KiB
Java
package com.tongran.agent.client.utils;
|
|
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Paths;
|
|
import java.util.List;
|
|
|
|
public class CpuUsageFromProcStat {
|
|
|
|
private static final String PROC_STAT = "/proc/stat";
|
|
private static long[] prevCpuTime = null;
|
|
|
|
public static double getCpuUsage() throws Exception {
|
|
List<String> lines = Files.readAllLines(Paths.get(PROC_STAT));
|
|
for (String line : lines) {
|
|
if (line.startsWith("cpu ")) {
|
|
long[] current = parseCpuLine(line);
|
|
if (prevCpuTime == null) {
|
|
prevCpuTime = current;
|
|
Thread.sleep(500); // 初始等待
|
|
return 0.0; // 第一次不返回数据
|
|
}
|
|
|
|
double usage = calculateCpuUsage(prevCpuTime, current);
|
|
prevCpuTime = current; // 更新
|
|
return usage;
|
|
}
|
|
}
|
|
throw new RuntimeException("无法读取 /proc/stat 中的 cpu 数据");
|
|
}
|
|
|
|
private static long[] parseCpuLine(String line) {
|
|
String[] parts = line.split("\\s+");
|
|
// index: user, nice, system, idle, iowait, irq, softirq, steal
|
|
long user = Long.parseLong(parts[1]);
|
|
long nice = Long.parseLong(parts[2]);
|
|
long system = Long.parseLong(parts[3]);
|
|
long idle = Long.parseLong(parts[4]);
|
|
long iowait = Long.parseLong(parts[5]);
|
|
long irq = Long.parseLong(parts[6]);
|
|
long softirq = Long.parseLong(parts[7]);
|
|
|
|
long idleTotal = idle + iowait;
|
|
long systemTotal = user + nice + system + irq + softirq;
|
|
long total = idleTotal + systemTotal;
|
|
|
|
return new long[]{idleTotal, total};
|
|
}
|
|
|
|
private static double calculateCpuUsage(long[] prev, long[] curr) {
|
|
long idleDiff = curr[0] - prev[0];
|
|
long totalDiff = curr[1] - prev[1];
|
|
|
|
if (totalDiff <= 0) return 0.0;
|
|
|
|
return 1.0 - ((double) idleDiff / totalDiff);
|
|
}
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
// 预热
|
|
getCpuUsage();
|
|
Thread.sleep(1000);
|
|
|
|
// 正式采集
|
|
for (int i = 0; i < 5; i++) {
|
|
double usage = getCpuUsage();
|
|
System.out.printf("CPU 使用率: %.2f%%\n", usage * 100);
|
|
Thread.sleep(2000);
|
|
}
|
|
}
|
|
} |