• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yxchun

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

获取某个进程占用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;
    }
}
View Code

需要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();

 

posted on 2022-08-06 16:22  yxchun  阅读(599)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3