Emmagee學習之獲取內存及CPU占用等數據

分類:技術 時間:2016-10-25

Emmagee 是網易杭州研究院QA團隊開發的一個簡單易上手的Android性能監測小工具,主要用于監控單個App的CPU,內存,流量,啟動耗時,電量,電流等性能狀態的變化,且用戶可自定義配置監控的頻率以及性能的實時顯示,并最終生成一份性能統計文件。

這里寫圖片描述

測試QQ的效果如下:

這里寫圖片描述

/**
     *  通過pid獲取應用占用的內存
     * @return
     */
    public int getPidMemorySize(int pid, Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        int[] myMempid = new int[] { pid };
        Debug.MemoryInfo[] memoryInfo = am.getProcessMemoryInfo(myMempid);
        memoryInfo[0].getTotalSharedDirty();
        int memSize = memoryInfo[0].getTotalPss();
        return memSize;
    }
/**
     * 獲取設備可用內存
     */
    public long getFreeMemorySize(Context context) {
        ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        am.getMemoryInfo(outInfo);
        long avaliMem = outInfo.availMem;
        return avaliMem / 1024;
    }
/**
     * 獲取設備總內存
     */
    public long getTotalMemory() {
        String memInfoPath = quot;/proc/meminfoquot;;
        String readTemp = quot;quot;;
        String memTotal = quot;quot;;
        long memory = 0;
        try {
            FileReader fr = new FileReader(memInfoPath);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            while ((readTemp = localBufferedReader.readLine()) != null) {
                if (readTemp.contains(quot;MemTotalquot;)) {
                    String[] total = readTemp.split(quot;:quot;);
                    memTotal = total[1].trim();
                }
            }
            localBufferedReader.close();
            String[] memKb = memTotal.split(quot; quot;);
            memTotal = memKb[0].trim();
            Log.d(LOG_TAG, quot;memTotal: quot;   memTotal);
            memory = Long.parseLong(memTotal);
        } catch (IOException e) {
            Log.e(LOG_TAG, quot;IOException: quot;   e.getMessage());
        }
        return memory;
    }
/**
     * 獲取dalvik與native分別占用的內存,僅root可用
     */
    public static String[][] parseMeminfo(int pid) {

        boolean infoStart = false;
        // [][],00:native heap size,01:native heap alloc;10: dalvik heap
        // size,11: dalvik heap alloc
        String[][] heapData = http://www.tuicool.com/articles/new String[2][2];

        try {
            Runtime runtime = Runtime.getRuntime();
            process = runtime.exec(quot;suquot;);
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(quot;dumpsys meminfo quot;   pid   quot;/nquot;);
            os.writeBytes(quot;exit/nquot;);
            os.flush();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = quot;quot;;

            while ((line = bufferedReader.readLine()) != null) {
                line = line.trim();
                if (line.contains(quot;Permission Denialquot;)) {
                    break;
                } else {
                    // 當讀取到MEMINFO in pid 這一行時,下一行就是需要獲取的數據
                    if (line.contains(quot;MEMINFO in pidquot;)) {
                        infoStart = true;
                    } else if (infoStart) {
                        String[] lineItems = line.split(quot;//s quot;);
                        int length = lineItems.length;
                        if (line.startsWith(quot;sizequot;)) {
                            heapData[0][0] = lineItems[1];
                            heapData[1][0] = lineItems[2];
                        } else if (line.startsWith(quot;allocatedquot;)) {
                            heapData[0][1] = lineItems[1];
                            heapData[1][1] = lineItems[2];
                            break;
                        } else if (line.startsWith(quot;Nativequot;)) {
                            Log.d(LOG_TAG, quot;Nativequot;);
                            Log.d(LOG_TAG, quot;lineItems[4]=quot;   lineItems[4]);
                            Log.d(LOG_TAG, quot;lineItems[5]=quot;   lineItems[5]);
                            heapData[0][0] = lineItems[length-3];
                            heapData[0][1] = lineItems[length-2];
                        } else if (line.startsWith(quot;Dalvikquot;)) {
                            Log.d(LOG_TAG, quot;Dalvikquot;);
                            Log.d(LOG_TAG, quot;lineItems[4]=quot;   lineItems[4]);
                            Log.d(LOG_TAG, quot;lineItems[5]=quot;   lineItems[5]);
                            heapData[1][0] = lineItems[length-3];
                            heapData[1][1] = lineItems[length-2];
                            break;
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return heapData;
    }
/**
     * 獲取cpu個數,即處理器核心數
     * @return
     */
    public int getCpuNum() {
        try {
            // Get directory containing CPU info
            File dir = new File(quot;/sys/devices/system/cpu/quot;);
            // Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            return files.length;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }
/**
     * 獲取cpu列表
     */
    public ArrayListlt;Stringgt; getCpuList() {
        ArrayListlt;Stringgt; cpuList = new ArrayListlt;Stringgt;();
        try {
            // Get directory containing CPU info
            File dir = new File(quot;/sys/devices/system/cpu/quot;);
            // Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            for (int i = 0; i lt; files.length; i  ) {
                cpuList.add(files[i].getName());
            }
            return cpuList;
        } catch (Exception e) {
            e.printStackTrace();
            cpuList.add(quot;cpu0quot;);
            return cpuList;
        }
    }
public String getCpuName() {
        try {
            RandomAccessFile cpuStat = new RandomAccessFile(quot;/proc/cpuinfoquot;, quot;rquot;);
            // check cpu type
            String line;
            while (null != (line = cpuStat.readLine())) {
                String[] values = line.split(quot;:quot;);
                if (values[0].contains(quot;model namequot;) || values[0].contains(quot;Processorquot;)) {
                    cpuStat.close();
                    Log.d(LOG_TAG, quot;CPU name=quot; values[1]);
                    return values[1];
                }
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, quot;IOException: quot;   e.getMessage());
        }
        return quot;quot;;
    }
/**
     * 獲取網絡流量,上傳和下載的總和
     */
    public long getTrafficInfo() {
        Log.i(LOG_TAG, quot;get traffic informationquot;);

        long rcvTraffic = -1;
        long sndTraffic = -1;

        // Use getUidRxBytes and getUidTxBytes to get network traffic,these API
        // return both tcp and udp usage
        rcvTraffic = TrafficStats.getUidRxBytes(Integer.parseInt(uid));
        sndTraffic = TrafficStats.getUidTxBytes(Integer.parseInt(uid));

        if (rcvTraffic == -1 || sndTraffic == -1) {
            return -1;
        } else
            return rcvTraffic   sndTraffic;
    }

cpu使用率的計算稍微有些不同:

// 先獲取當前pid的占用情況
        String processPid = Integer.toString(pid);
        String cpuStatPath = quot;/proc/quot;   processPid   quot;/statquot;;
        try {
            // monitor cpu stat of certain process
            RandomAccessFile processCpuInfo = new RandomAccessFile(cpuStatPath, quot;rquot;);
            String line = quot;quot;;
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.setLength(0);
            while ((line = processCpuInfo.readLine()) != null) {
                stringBuffer.append(line   quot;\nquot;);
            }
            String[] tok = stringBuffer.toString().split(quot; quot;);
            processCpu = Long.parseLong(tok[13])   Long.parseLong(tok[14]);
            processCpuInfo.close();
        } catch (FileNotFoundException e) {
            Log.w(LOG_TAG, quot;FileNotFoundException: quot;   e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
// 再獲取總的cpu使用情況
        try {
            // monitor total and idle cpu stat of certain process
            RandomAccessFile cpuInfo = new RandomAccessFile(CPU_STAT, quot;rquot;);
            String line = quot;quot;;
            while ((null != (line = cpuInfo.readLine())) amp;amp; line.startsWith(quot;cpuquot;)) {
                String[] toks = line.split(quot;\\s quot;);
                idleCpu.add(Long.parseLong(toks[4]));
                totalCpu.add(Long.parseLong(toks[1])   Long.parseLong(toks[2])   Long.parseLong(toks[3])   Long.parseLong(toks[4])
                          Long.parseLong(toks[6])   Long.parseLong(toks[5])   Long.parseLong(toks[7]));
            }
            cpuInfo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

當前進行所占CPU的算法是:100*(processCpuTimeS-processCpuTimeF) / (totalCpuTimeS-totalCpuTimeF)

CPU總數用率的算法是:100*((totalCpuTimeS-totalCpuTimeF) - (idelS-idelF)) / (totalCpuTimeS - totalCpuTimeF)

參考: http://blog.csdn.net/l2show/article/details/40950657

if (null != totalCpu2 amp;amp; totalCpu2.size() gt; 0) {
                    processCpuRatio = fomart.format(100 * ((double) (processCpu - processCpu2) / ((double) (totalCpu.get(0) - totalCpu2.get(0)))));

                    for (int i = 0; i lt; (totalCpu.size() gt; totalCpu2.size() ? totalCpu2.size() : totalCpu.size()); i  ) {
                        String cpuRatio = quot;0.00quot;;
                        if (totalCpu.get(i) - totalCpu2.get(i) gt; 0) {
                            cpuRatio = fomart
                                    .format(100 * ((double) ((totalCpu.get(i) - idleCpu.get(i)) - (totalCpu2.get(i) - idleCpu2.get(i))) / (double) (totalCpu
                                            .get(i) - totalCpu2.get(i))));
                        }
                        totalCpuRatio.add(cpuRatio);
                        totalCpuBuffer.append(cpuRatio   Constants.COMMA);
                    }
                } else { // 保存前一次的cpu使用情況
                    processCpuRatio = quot;0quot;;
                    totalCpuRatio.add(quot;0quot;);
                    totalCpuBuffer.append(quot;0,quot;);
                    totalCpu2 = (ArrayListlt;Longgt;) totalCpu.clone();
                    processCpu2 = processCpu;
                    idleCpu2 = (ArrayListlt;Longgt;) idleCpu.clone();
                }

CodeBlog 是我做的一個編程技術學習客戶端,集成了很多技術網站上的博客, 應用寶詳情頁


Tags: 安卓開發

文章來源:http://www.jianshu.com/p/220b2873cb4e


ads
ads

相關文章
ads

相關文章

ad