获取CPU的使用率

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;

public class CPULoad {
	
	private static int CPU_SLEEP_TIME = 3000;

	private static long[] getCpuInfo() throws IOException {
		long TOTAL, USER, NICE, SYSTEM, IDLE,IOWAIT,IRQ,SOFTIRQ;
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/stat")), 1000);
		String load = reader.readLine();
		reader.close();
		String[] toks = load.split(" ");
		USER = Long.parseLong(toks[2]);
		NICE = Long.parseLong(toks[3]);
		SYSTEM = Long.parseLong(toks[4]);
		IDLE = Long.parseLong(toks[5]);
		IOWAIT = Long.parseLong(toks[6]);
		IRQ = Long.parseLong(toks[7]);
		SOFTIRQ = Long.parseLong(toks[8]);
		TOTAL=USER+NICE+SYSTEM+IDLE+IOWAIT+IRQ+SOFTIRQ;
		return new long[] {TOTAL, USER, NICE, SYSTEM, IDLE,IOWAIT,IRQ,SOFTIRQ};
	}
	public static float readUsage() throws InterruptedException, IOException {
		long[] cpuInfo_1 = getCpuInfo();
		long TOTLE_1;
		TOTLE_1 = cpuInfo_1[0];
		Thread.sleep(CPU_SLEEP_TIME);
		long[] cpuInfo_2 = getCpuInfo();
		long TOTLE_2;
		TOTLE_2 = cpuInfo_2[0];
		float usage =  (((float) ((cpuInfo_2[1] + cpuInfo_2[3]) - (cpuInfo_1[1] + cpuInfo_1[3])) / (float) (TOTLE_2 - TOTLE_1)) * 100);
		BigDecimal   b   =   new   BigDecimal(usage);
		usage   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).floatValue();
		return usage;
	}

	public static void main(String args[]) throws Exception {
		for (int i = 0; i < 100; i++) {
			System.out.println(">>>>>>>>\t" + readUsage());
			Thread.sleep(1000);
		}
	}

}

你可能感兴趣的:(cpu,使用率,/proc/stat)