获取某个进程占用CPU比例,并将执行结果存到文件中
获取CPU占用率计算公式
allProcessTime_1 = 所有进程的KernelModeTime+UserModeTime
SystemProcessTime_1 = System Idle Process 进程的 KernelModeTime+UserModeTime 【 System Idle Process 是系统空闲进程】
间隔几秒后,再次取得上面的值
allProcessTime_2 = 所有进程的KernelModeTime+UserModeTime
SystemProcessTime_2 = System Idle Process 进程的 KernelModeTime+UserModeTime
busyTime = allProcessTime_2 - allProcessTime_1
idleTime = SystemProcessTime_2 - SystemProcessTime_1
CPU占用率 = busyTime / (busyTime+idleTime )
单个进程CPU占用率 = 单个进程的busyTime / (busyTime+idleTime )
不正确地方请指教
源码:
package test02.getCPU; import com.alibaba.fastjson.JSON; import test02.getCPU.CPUUtilization; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Author yxchun * @date 2022/8/3 11:15 * @Des 获取某个进程占用总CPU比例 **/ public class UsedCPU6 { private static List<String> specifiedCaption=new ArrayList<String>(); private static File file = new File("D:\\file\\logs\\cpu.txt"); public static void main(String[] args) throws IOException { specifiedCaption.add("java.exe"); specifiedCaption.add("idea64.exe"); if(!file.exists()){ file.createNewFile(); } while(true){ BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true))); //windows进程获取某进程所占用CPU,以及整体CPU使用 String thecpuUtilization = getCpuRatioForWindows(); bw.write(thecpuUtilization); bw.newLine(); bw.flush(); } } private static String getCpuRatioForWindows() { try { String procCmd = System.getenv("windir") + "\\system32\\wbem\\wmic.exe process get Caption," + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount"; // 取进程信息 long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd)).get(1); long[] spec0 = readCpu(Runtime.getRuntime().exec(procCmd)).get(2); Thread.sleep(2000); long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd)).get(1); long[] spec1 = readCpu(Runtime.getRuntime().exec(procCmd)).get(2); List<CPUUtilization> cpuLists = new ArrayList<>(); if (c0 != null && c1 != null) { long idletime = c1[0] - c0[0]; long busytime = c1[1] - c0[1]; for (int i =0;i<specifiedCaption.size(); i++){ long specifiedTime = spec1[i]-spec0[i]; // System.out.println("进程"+specifiedCaption.get(i)+" CPU占用率"+Double.valueOf(100 * (specifiedTime) / (busytime + idletime)).doubleValue()); CPUUtilization cpuUtilization = new CPUUtilization(); cpuUtilization.setCaption(specifiedCaption.get(i)); cpuUtilization.setUtilization(Double.valueOf(100 * (specifiedTime) / (busytime + idletime)).doubleValue()); cpuLists.add(cpuUtilization); } CPUUtilization allcpuUtilization = new CPUUtilization(); allcpuUtilization.setCaption("all cpuUtilization"); allcpuUtilization.setUtilization(Double.valueOf(100 * (busytime) / (busytime + idletime)).doubleValue()); cpuLists.add(allcpuUtilization); return JSON.toJSONString(cpuLists); } return null; } catch (Exception ex) { ex.printStackTrace(); return null; } } public static Map<Integer,long[]> readCpu(final Process proc) { long[] retn = new long[3]; long[] specified = new long[specifiedCaption.size()]; // String specifiedName=null; for(String str:specifiedCaption){ specifiedName+=str; } try { proc.getOutputStream().close(); InputStreamReader ir = new InputStreamReader(proc.getInputStream()); LineNumberReader input = new LineNumberReader(ir); // 这里是指读到第一行,也就是 :Caption KernelModeTime ReadOperationCount ThreadCount UserModeTime WriteOperationCount String line = input.readLine(); if (line == null || line.length() < 10) { return null; } int capidx = line.indexOf("Caption"); int kmtidx = line.indexOf("KernelModeTime"); int rocidx = line.indexOf("ReadOperationCount"); int umtidx = line.indexOf("UserModeTime"); int wocidx = line.indexOf("WriteOperationCount"); long idletime = 0; long kneltime = 0; long usertime = 0; //从第二行开始读 while ((line = input.readLine()) != null) { if (line.length() < wocidx) { // System.out.println("xiaoyu \t line.length()="+line.length()+"\t wocidx="+wocidx); continue; } // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount, // ThreadCount,UserModeTime,WriteOperation String caption = substring(line, capidx, kmtidx - 1).trim(); // String cmd = substring(line, cmdidx, kmtidx - 1).trim(); //返回此字符串中第一次出现指定子字符串的索引。 if (caption.indexOf("wmic.exe") >= 0) { continue; } if (caption.equals("System Idle Process") || caption.equals("System")) { idletime += Long.valueOf(substring(line, kmtidx, rocidx - 1).trim()).longValue(); idletime += Long.valueOf(substring(line, umtidx, wocidx - 1).trim()).longValue(); continue; } //如果现在的caption在specifiedName里面,就进入计算 if(specifiedName.contains(caption)){ for(int i=0;i<specifiedCaption.size();i++){ if(caption.equals(specifiedCaption.get(i))){ specified[i] += Long.valueOf(substring(line, kmtidx, rocidx - 1).trim()).longValue(); specified[i] += Long.valueOf(substring(line, umtidx, wocidx - 1).trim()).longValue(); } } } kneltime += Long.valueOf(substring(line, kmtidx, rocidx - 1).trim()).longValue(); usertime += Long.valueOf(substring(line, umtidx, wocidx - 1).trim()).longValue(); } retn[0] = idletime; retn[1] = kneltime + usertime; Map<Integer,long[]> maps = new HashMap<>(); maps.put(1,retn); maps.put(2,specified); return maps; } catch (Exception ex) { ex.printStackTrace(); } finally { try { proc.getInputStream().close(); } catch (Exception e) { e.printStackTrace(); } } return null; } public static String substring(String src, int start_idx, int end_idx) { byte[] b = src.getBytes(); String tgt = ""; for (int i = start_idx; i <= end_idx; i++) { tgt += (char) b[i]; } return tgt; } }
CPUUtilization.java

package test02.getCPU; /** * @Author yxchun * @date 2022/8/6 13:16 * @Des **/ public class CPUUtilization { private String caption; private double utilization; public CPUUtilization(){} public CPUUtilization(String caption, double utilization) { this.caption = caption; this.utilization = utilization; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public double getUtilization() { return utilization; } public void setUtilization(double utilization) { this.utilization = utilization; } }
需要jar包
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency>
解析:
执行cmd命令
String procCmd = System.getenv("windir") + "\\system32\\wbem\\wmic.exe process get Caption," + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
执行结果
分别获取Caption,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount 的起始位置,便于后续字符串截取
int capidx = line.indexOf("Caption"); int kmtidx = line.indexOf("KernelModeTime"); int rocidx = line.indexOf("ReadOperationCount"); int umtidx = line.indexOf("UserModeTime"); int wocidx = line.indexOf("WriteOperationCount");
截取字符串line,从capidx 到kmtidx - 1 的字符,并去除空格;
String caption = substring(line, capidx, kmtidx - 1).trim();
比如:
同样地:获取SystemProcessTime
代码1: idletime += Long.valueOf(substring(line, kmtidx, rocidx - 1).trim()).longValue(); 代码2: idletime += Long.valueOf(substring(line, umtidx, wocidx - 1).trim()).longValue();
代码1:
代码2
同样地,获取allProcessTime
kneltime += Long.valueOf(substring(line, kmtidx, rocidx - 1).trim()).longValue(); usertime += Long.valueOf(substring(line, umtidx, wocidx - 1).trim()).longValue();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~