天天看點

擷取系統CPU及記憶體使用情況

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ithings.compframe;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;


/**
 * @Title: SystemInfoUtil.class
 * @Description:擷取windows系統資訊(CPU,記憶體,檔案系統)
 */
public class SystemInfoUtil {

    /**
     * 目前cpu的使用率
     * @return
     */
    public static Float getCompCpuStatus() {
        float userCpuUtilization = 0;
        //不管是單塊CPU還是多CPU都适用
        CpuPerc cpuList[] = null;
        Sigar sigar = new Sigar();
        try {
            cpuList = sigar.getCpuPercList();
        } catch (SigarException e) {
            e.printStackTrace();
            return userCpuUtilization;
        }
        for (int i = 0; i < cpuList.length; i++) {
            userCpuUtilization += printCpuPerc(cpuList[i]);
        }
//        System.out.println("CPU使用效率:" + CpuPerc.format(dombined));
        return userCpuUtilization * 100;
    }

    private static double printCpuPerc(CpuPerc cpu) {
        return cpu.getUser();
    }

    /**
     * 記憶體資源資訊
     * @return
     */
    public static int getCompPhysicalMemory() {
        Sigar sigar = new Sigar();
        int memory = 0;
        try {
            // 目前記憶體使用量
            memory = new Long((sigar.getMem().getUsed() / 1024 / 1024)).intValue();
        } catch (SigarException e) {
            e.printStackTrace();
        } finally {
            return memory;
        }
    }
}
           

繼續閱讀