Emmagee學(xué)習(xí)之獲取內(nèi)存及CPU占用等數(shù)據(jù)

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

這里寫圖片描述

測試QQ的效果如下:


這里寫圖片描述
    /**
     *  通過pid獲取應(yīng)用占用的內(nèi)存
     * @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;
    }
    /**
     * 獲取設(shè)備可用內(nèi)存
     */
    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;
    }

    /**
     * 獲取設(shè)備總內(nèi)存
     */
    public long getTotalMemory() {
        String memInfoPath = "/proc/meminfo";
        String readTemp = "";
        String memTotal = "";
        long memory = 0;
        try {
            FileReader fr = new FileReader(memInfoPath);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            while ((readTemp = localBufferedReader.readLine()) != null) {
                if (readTemp.contains("MemTotal")) {
                    String[] total = readTemp.split(":");
                    memTotal = total[1].trim();
                }
            }
            localBufferedReader.close();
            String[] memKb = memTotal.split(" ");
            memTotal = memKb[0].trim();
            Log.d(LOG_TAG, "memTotal: " + memTotal);
            memory = Long.parseLong(memTotal);
        } catch (IOException e) {
            Log.e(LOG_TAG, "IOException: " + e.getMessage());
        }
        return memory;
    }
    /**
     * 獲取dalvik與native分別占用的內(nèi)存,僅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 = new String[2][2];

        try {
            Runtime runtime = Runtime.getRuntime();
            process = runtime.exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            os.writeBytes("dumpsys meminfo " + pid + "\n");
            os.writeBytes("exit\n");
            os.flush();

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

            while ((line = bufferedReader.readLine()) != null) {
                line = line.trim();
                if (line.contains("Permission Denial")) {
                    break;
                } else {
                    // 當(dāng)讀取到MEMINFO in pid 這一行時,下一行就是需要獲取的數(shù)據(jù)
                    if (line.contains("MEMINFO in pid")) {
                        infoStart = true;
                    } else if (infoStart) {
                        String[] lineItems = line.split("\\s+");
                        int length = lineItems.length;
                        if (line.startsWith("size")) {
                            heapData[0][0] = lineItems[1];
                            heapData[1][0] = lineItems[2];
                        } else if (line.startsWith("allocated")) {
                            heapData[0][1] = lineItems[1];
                            heapData[1][1] = lineItems[2];
                            break;
                        } else if (line.startsWith("Native")) {
                            Log.d(LOG_TAG, "Native");
                            Log.d(LOG_TAG, "lineItems[4]=" + lineItems[4]);
                            Log.d(LOG_TAG, "lineItems[5]=" + lineItems[5]);
                            heapData[0][0] = lineItems[length-3];
                            heapData[0][1] = lineItems[length-2];
                        } else if (line.startsWith("Dalvik")) {
                            Log.d(LOG_TAG, "Dalvik");
                            Log.d(LOG_TAG, "lineItems[4]=" + lineItems[4]);
                            Log.d(LOG_TAG, "lineItems[5]=" + lineItems[5]);
                            heapData[1][0] = lineItems[length-3];
                            heapData[1][1] = lineItems[length-2];
                            break;
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return heapData;
    }
    /**
     * 獲取cpu個數(shù),即處理器核心數(shù)
     * @return
     */
    public int getCpuNum() {
        try {
            // Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            // 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 ArrayList<String> getCpuList() {
        ArrayList<String> cpuList = new ArrayList<String>();
        try {
            // Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            // Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            for (int i = 0; i < files.length; i++) {
                cpuList.add(files[i].getName());
            }
            return cpuList;
        } catch (Exception e) {
            e.printStackTrace();
            cpuList.add("cpu0");
            return cpuList;
        }
    }
    public String getCpuName() {
        try {
            RandomAccessFile cpuStat = new RandomAccessFile("/proc/cpuinfo", "r");
            // check cpu type
            String line;
            while (null != (line = cpuStat.readLine())) {
                String[] values = line.split(":");
                if (values[0].contains("model name") || values[0].contains("Processor")) {
                    cpuStat.close();
                    Log.d(LOG_TAG, "CPU name="+values[1]);
                    return values[1];
                }
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "IOException: " + e.getMessage());
        }
        return "";
    }
    /**
     * 獲取網(wǎng)絡(luò)流量,上傳和下載的總和
     */
    public long getTrafficInfo() {
        Log.i(LOG_TAG, "get traffic information");

        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使用率的計算稍微有些不同:

// 先獲取當(dāng)前pid的占用情況
        String processPid = Integer.toString(pid);
        String cpuStatPath = "/proc/" + processPid + "/stat";
        try {
            // monitor cpu stat of certain process
            RandomAccessFile processCpuInfo = new RandomAccessFile(cpuStatPath, "r");
            String line = "";
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.setLength(0);
            while ((line = processCpuInfo.readLine()) != null) {
                stringBuffer.append(line + "\n");
            }
            String[] tok = stringBuffer.toString().split(" ");
            processCpu = Long.parseLong(tok[13]) + Long.parseLong(tok[14]);
            processCpuInfo.close();
        } catch (FileNotFoundException e) {
            Log.w(LOG_TAG, "FileNotFoundException: " + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
// 再獲取總的cpu使用情況
        try {
            // monitor total and idle cpu stat of certain process
            RandomAccessFile cpuInfo = new RandomAccessFile(CPU_STAT, "r");
            String line = "";
            while ((null != (line = cpuInfo.readLine())) && line.startsWith("cpu")) {
                String[] toks = line.split("\\s+");
                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();
        }

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

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

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

                if (null != totalCpu2 && totalCpu2.size() > 0) {
                    processCpuRatio = fomart.format(100 * ((double) (processCpu - processCpu2) / ((double) (totalCpu.get(0) - totalCpu2.get(0)))));
                    
                    for (int i = 0; i < (totalCpu.size() > totalCpu2.size() ? totalCpu2.size() : totalCpu.size()); i++) {
                        String cpuRatio = "0.00";
                        if (totalCpu.get(i) - totalCpu2.get(i) > 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 = "0";
                    totalCpuRatio.add("0");
                    totalCpuBuffer.append("0,");
                    totalCpu2 = (ArrayList<Long>) totalCpu.clone();
                    processCpu2 = processCpu;
                    idleCpu2 = (ArrayList<Long>) idleCpu.clone();
                }

CodeBlog是我做的一個編程技術(shù)學(xué)習(xí)客戶端,集成了很多技術(shù)網(wǎng)站上的博客,應(yīng)用寶詳情頁

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,527評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,687評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,640評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,957評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,682評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,011評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,009評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,183評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,714評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,435評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,665評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,148評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,838評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,251評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,588評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,379評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,627評論 2 380

推薦閱讀更多精彩內(nèi)容