Rising Sun

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            148 隨筆 :: 0 文章 :: 22 評(píng)論 :: 0 Trackbacks
            private static double getCpuRateForLinux(){
                  InputStream is = null;
                  InputStreamReader isr = null;
                  BufferedReader brStat = null;
                  StringTokenizer tokenStat = null;
                  try{
                      System.out.println("Get usage rate of CUP , linux version: "+linuxVersion);
                      Process process = Runtime.getRuntime().exec("top -b -n 1");
                      is = process.getInputStream();
                      isr = new InputStreamReader(is);
                      brStat = new BufferedReader(isr);
                      if(linuxVersion.equals("2.4")){
                          brStat.readLine();
                          brStat.readLine();
                          brStat.readLine();
                          brStat.readLine();
                          tokenStat = new StringTokenizer(brStat.readLine());
                          tokenStat.nextToken();
                          tokenStat.nextToken();
                          String user = tokenStat.nextToken();
                          tokenStat.nextToken();
                          String system = tokenStat.nextToken();
                          tokenStat.nextToken();
                          String nice = tokenStat.nextToken();
                          System.out.println(user+" , "+system+" , "+nice);
                          user = user.substring(0,user.indexOf("%"));
                          system = system.substring(0,system.indexOf("%"));
                          nice = nice.substring(0,nice.indexOf("%"));
                          float userUsage = new Float(user).floatValue();
                          float systemUsage = new Float(system).floatValue();
                          float niceUsage = new Float(nice).floatValue();
                          return (userUsage+systemUsage+niceUsage)/100;
                      }else{
                          brStat.readLine();
                          brStat.readLine();
                          tokenStat = new StringTokenizer(brStat.readLine());
                          tokenStat.nextToken();
                          tokenStat.nextToken();
                          tokenStat.nextToken();
                          tokenStat.nextToken();
                          tokenStat.nextToken();
                          tokenStat.nextToken();
                          tokenStat.nextToken();
                          String cpuUsage = tokenStat.nextToken();
                          System.out.println("CPU idle : "+cpuUsage);
                          Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf("%")));
                          return (1-usage.floatValue()/100);
                      }
                  } catch(IOException ioe){
                      System.out.println(ioe.getMessage());
                      freeResource(is, isr, brStat);
                      return 1;
                  } finally{
                      freeResource(is, isr, brStat);
                  }
              }
              private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br){
                  try{
                      if(is!=null)
                          is.close();
                      if(isr!=null)
                          isr.close();
                      if(br!=null)
                          br.close();
                  }catch(IOException ioe){
                      System.out.println(ioe.getMessage());
                  }
              }
              /**
               * 獲得CPU使用率.   
               * @return 返回cpu使用率
               * @author GuoHuang
               */
              private double getCpuRatioForWindows() {
                  try {
                      String procCmd = System.getenv("windir")
                              + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"
                              + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
                      // 取進(jìn)程信息    
                      long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
                      Thread.sleep(CPUTIME);
                      long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
                      if (c0 != null && c1 != null) {
                          long idletime = c1[0] - c0[0];
                          long busytime = c1[1] - c0[1];
                          return Double.valueOf(
                                  PERCENT * (busytime) / (busytime + idletime))
                                  .doubleValue();
                      } else {
                          return 0.0;
                      }
                  } catch (Exception ex) {
                      ex.printStackTrace();
                      return 0.0;
                  }
              }
              /**
               * 讀取CPU信息.
               * @param proc
               * @return
               * @author GuoHuang
               */
              private long[] readCpu(final Process proc) {
                  long[] retn = new long[2];
                  try {
                      proc.getOutputStream().close();
                      InputStreamReader ir = new InputStreamReader(proc.getInputStream());
                      LineNumberReader input = new LineNumberReader(ir);
                      String line = input.readLine();
                      if (line == null || line.length() < FAULTLENGTH) {
                          return null;
                      }
                      int capidx = line.indexOf("Caption");
                      int cmdidx = line.indexOf("CommandLine");
                      int rocidx = line.indexOf("ReadOperationCount");
                      int umtidx = line.indexOf("UserModeTime");
                      int kmtidx = line.indexOf("KernelModeTime");
                      int wocidx = line.indexOf("WriteOperationCount");
                      long idletime = 0;
                      long kneltime = 0;
                      long usertime = 0;
                      while ((line = input.readLine()) != null) {
                          if (line.length() < wocidx) {
                              continue;
                          }
                          // 字段出現(xiàn)順序:Caption,CommandLine,KernelModeTime,ReadOperationCount,    
                          // ThreadCount,UserModeTime,WriteOperation    
                          String caption = Bytes.substring(line, capidx, cmdidx - 1)
                                  .trim();
                          String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
                          if (cmd.indexOf("wmic.exe") >= 0) {
                              continue;
                          }
                          // log.info("line="+line);    
                          if (caption.equals("System Idle Process")
                                  || caption.equals("System")) {
                              idletime += Long.valueOf(
                                      Bytes.substring(line, kmtidx, rocidx - 1).trim())
                                      .longValue();
                              idletime += Long.valueOf(
                                      Bytes.substring(line, umtidx, wocidx - 1).trim())
                                      .longValue();
                              continue;
                          }
                          kneltime += Long.valueOf(
                                  Bytes.substring(line, kmtidx, rocidx - 1).trim())
                                  .longValue();
                          usertime += Long.valueOf(
                                  Bytes.substring(line, umtidx, wocidx - 1).trim())
                                  .longValue();
                      }
                      retn[0] = idletime;
                      retn[1] = kneltime + usertime;
                      return retn;
                  } catch (Exception ex) {
                      ex.printStackTrace();
                  } finally {
                      try {
                          proc.getInputStream().close();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                  }
                  return null;
              }
          上面方法不行,下面的可以
            String result = "";
                  try {
                      File file = File.createTempFile("tmp", ".vbs");
                      file.deleteOnExit();
                      FileWriter fw = new java.io.FileWriter(file);
                      String vbs ="Set objProc = GetObject(\"winmgmts:\\\\.\\root\\cimv2:win32_processor='cpu0'\")\n" +
                              "WScript.Echo  \"CPU Load Percentage: \"& chr(13) & chr(10) & Round(objProc.LoadPercentage,2) & \"%\"";
                      fw.write(vbs);
                      fw.close();
                      Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
                      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                      String line;
                      while ((line = input.readLine()) != null) {
                          result += line;
                      }
                      input.close();
                      file.delete();
                  } catch (Exception e) {
                      e.fillInStackTrace();
                  }
                  if (result.trim().length() < 1 || result == null) {
                  }else{
                      System.out.println(result.trim());
                  }




          posted on 2013-08-19 10:40 brock 閱讀(723) 評(píng)論(0)  編輯  收藏 所屬分類: 學(xué)習(xí)總結(jié)
          主站蜘蛛池模板: 嵊泗县| 晋中市| 丰都县| 星座| 鹤岗市| 中江县| 云浮市| 麻栗坡县| 西乌珠穆沁旗| 阿勒泰市| 左权县| 阳朔县| 香格里拉县| 定襄县| 周宁县| 芒康县| 哈密市| 清苑县| 皋兰县| 开江县| 利辛县| 沙河市| 五大连池市| 古丈县| 十堰市| 湟中县| 韶关市| 高碑店市| 平顶山市| 竹溪县| 酉阳| 开江县| 平遥县| 垫江县| 海兴县| 苍梧县| 巫山县| 大邑县| 庆阳市| 灌云县| 常德市|