參考自 這理
前言 :
最近做個項目,就是要取得cpu佔有率等等的系統信息,一開始以為要用動態鏈接庫了,但後來發現可以像下面這樣做,不去調用jni,這樣省去了很多JNI 所帶來的 effort. 在Java中,可以獲得總的物理內存、剩餘的物理內存、已使用的物理內存等信息,下面例子可以取得這些信息,並且獲得在Windows下的內存使用率.
實作過程 :
首先編寫一個 MonitorInfoBean 類,用來裝載監控的一些信息,包括物理內存、剩餘的物理內存、已使用的物理內存、內存使用率等字段,該類的代碼如下 :
接著編寫一個獲得當前的監控信息的接口,該類的代碼如下所示 :
該類的實現類MonitorServiceImpl如下所示 :
該實現類中需要用到一個自己編寫byte的工具類,該類的代碼如下所示 :
測試結果 :
測試我們可以建立一個 MonitorServiceImpl 類別的實例, 在一建立時例後 MonitorServiceImpl 會立即取得當下的 CPU 相關初始訊息. 接著我們讓當前線程 Sleep 6 秒後在呼叫 getMonitorInfoBean() 函式已取的相關系統訊息, 測試代碼如下 :
執行結果 :
補充說明 :
* [Windows 技巧] wmic 使用簡介
前言 :
最近做個項目,就是要取得cpu佔有率等等的系統信息,一開始以為要用動態鏈接庫了,但後來發現可以像下面這樣做,不去調用jni,這樣省去了很多JNI 所帶來的 effort. 在Java中,可以獲得總的物理內存、剩餘的物理內存、已使用的物理內存等信息,下面例子可以取得這些信息,並且獲得在Windows下的內存使用率.
實作過程 :
首先編寫一個 MonitorInfoBean 類,用來裝載監控的一些信息,包括物理內存、剩餘的物理內存、已使用的物理內存、內存使用率等字段,該類的代碼如下 :
- MonitorInfoBean.java : 裝載監控的信息Bean
- package perf.beans;
- public class MonitorInfoBean {
- /** */
- /** 可使用內存. */
- private long totalMemory;
- /** */
- /** 剩餘內存. */
- private long freeMemory;
- /** */
- /** 最大可使用內存. */
- private long maxMemory;
- /** */
- /** 操作系統. */
- private String osName;
- /** */
- /** 總物理內存. */
- private long totalMemorySize;
- /** */
- /** 剩餘的物理內存. */
- private long freePhysicalMemorySize;
- /** */
- /** 已使用的物理內存. */
- private long usedMemory;
- /** */
- /** 線程總數. */
- private int totalThread;
- /** */
- /** cpu使用率. */
- private double cpuRatio;
- public long getFreeMemory() {
- return freeMemory;
- }
- public void setFreeMemory(long freeMemory) {
- this.freeMemory = freeMemory;
- }
- public long getFreePhysicalMemorySize() {
- return freePhysicalMemorySize;
- }
- public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
- this.freePhysicalMemorySize = freePhysicalMemorySize;
- }
- public long getMaxMemory() {
- return maxMemory;
- }
- public void setMaxMemory(long maxMemory) {
- this.maxMemory = maxMemory;
- }
- public String getOsName() {
- return osName;
- }
- public void setOsName(String osName) {
- this.osName = osName;
- }
- public long getTotalMemory() {
- return totalMemory;
- }
- public void setTotalMemory(long totalMemory) {
- this.totalMemory = totalMemory;
- }
- public long getTotalMemorySize() {
- return totalMemorySize;
- }
- public void setTotalMemorySize(long totalMemorySize) {
- this.totalMemorySize = totalMemorySize;
- }
- public int getTotalThread() {
- return totalThread;
- }
- public void setTotalThread(int totalThread) {
- this.totalThread = totalThread;
- }
- public long getUsedMemory() {
- return usedMemory;
- }
- public void setUsedMemory(long usedMemory) {
- this.usedMemory = usedMemory;
- }
- public double getCpuRatio() {
- return cpuRatio;
- }
- public void setCpuRatio(double cpuRatio) {
- this.cpuRatio = cpuRatio;
- }
- }
接著編寫一個獲得當前的監控信息的接口,該類的代碼如下所示 :
- IMonitorService.java : 提供解耦合的介面
- package perf.proto;
- import perf.beans.MonitorInfoBean;
- public interface IMonitorService {
- /** *//**
- * 獲得當前監控對像.
- * @return 返回監測對象
- * @throws Exception
- */
- public MonitorInfoBean getMonitorInfoBean() throws Exception;
- }
該類的實現類MonitorServiceImpl如下所示 :
- MonitorServiceImpl.java : 獲取系統訊息的實作類別
- package perf.utils;
- import perf.beans.MonitorInfoBean;
- import perf.proto.IMonitorService;
- import java.io.InputStreamReader;
- import java.io.LineNumberReader;
- import sun.management.ManagementFactory;
- import com.sun.management.OperatingSystemMXBean;
- public class MonitorServiceImpl implements IMonitorService{
- public static final int CPUTIME = 5000;
- private static final int PERCENT = 100;
- private static final int FAULTLENGTH = 10;
- private static String PROC_CMD = System.getenv("windir")
- + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"
- + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
- private long[] initCpuInfo = null;
- public MonitorServiceImpl(){
- try{
- initCpuInfo = readCpu(Runtime.getRuntime().exec(PROC_CMD));
- }catch(Exception e){
- e.printStackTrace();
- initCpuInfo = null;
- }
- }
- @Override
- public MonitorInfoBean getMonitorInfoBean() throws Exception {
- int kb = 1024;
- // 可使用內存
- long totalMemory = Runtime.getRuntime().totalMemory() / kb;
- // 剩餘內存
- long freeMemory = Runtime.getRuntime().freeMemory() / kb;
- // 最大可使用內存
- long maxMemory = Runtime.getRuntime().maxMemory() / kb;
- OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
- .getOperatingSystemMXBean();
- // 操作系統
- String osName = System.getProperty("os.name");
- // 總物理內存
- long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
- // 剩餘的物理內存
- long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
- // 已使用的物理內存
- long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
- .getFreePhysicalMemorySize())
- / kb;
- // 獲得線程總數
- ThreadGroup parentThread;
- for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
- .getParent() != null; parentThread = parentThread.getParent())
- ;
- int totalThread = parentThread.activeCount();
- double cpuRatio = 0;
- if (osName.toLowerCase().startsWith("windows")) {
- cpuRatio = this.getCpuRatioForWindows();
- }
- // 返回對象
- MonitorInfoBean infoBean = new MonitorInfoBean();
- infoBean.setFreeMemory(freeMemory);
- infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
- infoBean.setMaxMemory(maxMemory);
- infoBean.setOsName(osName);
- infoBean.setTotalMemory(totalMemory);
- infoBean.setTotalMemorySize(totalMemorySize);
- infoBean.setTotalThread(totalThread);
- infoBean.setUsedMemory(usedMemory);
- infoBean.setCpuRatio(cpuRatio);
- return infoBean;
- }
- private double getCpuRatioForWindows() {
- try {
- if(initCpuInfo==null) return 0.0;
- // 取得進程信息
- //long[] c0 = readCpu(Runtime.getRuntime().exec(PROC_CMD));
- //Thread.sleep(CPUTIME);
- long[] c1 = readCpu(Runtime.getRuntime().exec(PROC_CMD));
- if (c1 != null) {
- long idletime = c1[0] - initCpuInfo[0];
- long busytime = c1[1] - initCpuInfo[1];
- return Double.valueOf(
- PERCENT * (busytime) / (busytime + idletime))
- .doubleValue();
- } else {
- return 0.0;
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- return 0.0;
- }
- }
- 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;
- }
- // 字段出現順序: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;
- }
- }
該實現類中需要用到一個自己編寫byte的工具類,該類的代碼如下所示 :
- Bytes.java : 解決 String.subString() 處理中文的問題 (將中文試為一個byte)
- package perf.utils;
- public class Bytes {
- 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;
- }
- }
測試結果 :
測試我們可以建立一個 MonitorServiceImpl 類別的實例, 在一建立時例後 MonitorServiceImpl 會立即取得當下的 CPU 相關初始訊息. 接著我們讓當前線程 Sleep 6 秒後在呼叫 getMonitorInfoBean() 函式已取的相關系統訊息, 測試代碼如下 :
- TMain.java : 測試類別
- package perf.test;
- import perf.beans.MonitorInfoBean;
- import perf.utils.MonitorServiceImpl;
- public class TMain {
- public static void main(String args[])
- {
- MonitorServiceImpl MSImpl = new MonitorServiceImpl();
- try {
- Thread.sleep(MonitorServiceImpl.CPUTIME);
- MonitorInfoBean bean = MSImpl.getMonitorInfoBean();
- System.out.println("OSName: "+bean.getOsName());
- System.out.println("CPU Ratio: "+bean.getCpuRatio());
- System.out.println("Available Mem in JVM: "+String.valueOf(bean.getTotalMemory()/1000.0)+" MB");
- System.out.println("Free Mem in JVM: "+bean.getFreeMemory()/1000.0+" MB");
- System.out.println("Max Available Mem for JVM: "+bean.getMaxMemory()/1000.0+" MB");
- System.out.println("============================");
- System.out.println("Total Pyysical Mem Size: "+bean.getTotalMemorySize()/1000.0+" MB");
- System.out.println("Total Physical Free Mem: "+bean.getFreePhysicalMemorySize()/1000.0+" MB");
- System.out.println("Total Physical Used Memory: "+bean.getUsedMemory()/1000.0+" MB");
- System.out.println("============================");
- System.out.println("Total Thread in Java: "+bean.getTotalThread());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
執行結果 :
OSName: Windows 7
CPU Ratio: 12.0
Available Mem in JVM: 79.296 MB
Free Mem in JVM: 55.281 MB
Max Available Mem for JVM: 932.096 MB
============================
Total Pyysical Mem Size: 4191.412 MB
Total Physical Free Mem: 1311.06 MB
Total Physical Used Memory: 2880.352 MB
============================
Total Thread in Java: 5
補充說明 :
* [Windows 技巧] wmic 使用簡介
wmic 是 Microsoft Windows Management Instrument 的縮寫. 提供了 Console mode 一個強而有力的 administrator 管理工具. 包或系統管理, 遠端主機訊息獲取到你想不到的更改主機名稱等功能都可以達成. 而 wmic 可以在路徑 C:\Windows\System32\wbem 下找到 (wmic.exe)...
This message was edited 3 times. Last update was at 26/05/2011 15:07:17
沒有留言:
張貼留言