获取系统(linux)cpu信息以及进程信息

 获取cpu使用信息:

public static float getCpuInfo() throws IOException, InterruptedException
  {
    File file = new File("/proc/stat");
    BufferedReader br = new BufferedReader(new InputStreamReader(
        new FileInputStream(file)));
    StringTokenizer token = new StringTokenizer(br.readLine());
    token.nextToken();
    int user1 = Integer.parseInt(token.nextToken());
    int nice1 = Integer.parseInt(token.nextToken());
    int sys1 = Integer.parseInt(token.nextToken());
    int idle1 = Integer.parseInt(token.nextToken());

    log.debug("user1===" + user1);
    log.debug("nice1===" + nice1);
    log.debug("sys1===" + sys1);
    log.debug("idle1===" + idle1);
    Thread.sleep(1000);
    br = new BufferedReader(
        new InputStreamReader(new FileInputStream(file)));
    token = new StringTokenizer(br.readLine());
    token.nextToken();
    int user2 = Integer.parseInt(token.nextToken());
    int nice2 = Integer.parseInt(token.nextToken());
    int sys2 = Integer.parseInt(token.nextToken());
    int idle2 = Integer.parseInt(token.nextToken());

    log.debug("user2===" + user2);
    log.debug("nice2===" + nice2);
    log.debug("sys2===" + sys2);
    log.debug("idle2===" + idle2);

    float cpuvalue = (user2 + nice2 + sys2 + idle2)
                     -
                     (user1 + nice1 + sys1 + idle1);
    if (cpuvalue == 0)
    {
      return 0;
    }
    log.debug("cpuvalue===" + cpuvalue);
    float getCpuvalue = (float) ( (user2 + sys2 + nice2)
                                 - (user1 + sys1 + nice1))
                        /
                        cpuvalue;
    log.debug("getCpuvalue===" + getCpuvalue);
    return getCpuvalue;
  }
获取进程信息:

 public static float[] getLoadAvgInfo() throws Exception
  {
    File file = new File("/proc/loadavg");
    BufferedReader br = new BufferedReader(new InputStreamReader(
        new FileInputStream(file)));
    String avgLine = br.readLine();
    String[] arvArray = avgLine.split("//s", 0);
    float[] floatAvgArray = new float[3];
    floatAvgArray[0] = Float.parseFloat(arvArray[0]);
    floatAvgArray[1] = Float.parseFloat(arvArray[1]);
    floatAvgArray[2] = Float.parseFloat(arvArray[2]);
    return floatAvgArray;
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值