---
title: "[Android]获取整体APP CPU信息"
author: "MyEyeOfJava"
date: "2015-01-07T14:34:55Z"
tags: []
categories: ["操作系统"]
slug: "android-app-cpu"
draft: false
lastmod: "2015-01-07T14:37:22Z"
id: 2173569
url: "https://myeyeofjava.iteye.com/blog/2173569"
---

通过proc获取CPU信息。  
adb shell cat /proc/stat | grep cpu &gt; totalcpu0  
此处第一行的数值表示的是CPU总的使用情况，所以我们只要用第一行的数字计算就可以了。下表解析第一行各数值的含义：  
参数 解析（单位：jiffies）  
(jiffies是内核中的一个全局变量，用来记录自系统启动一来产生的节拍数，在linux中，一个节拍大致可理解为操作系统进程调度的最小时间片，不同linux内核可能值有不同，通常在1ms到10ms之间)  
user 从系统启动开始累计到当前时刻，处于用户态的运行时间，不包含 nice值为负进程。  
nice 从系统启动开始累计到当前时刻，nice值为负的进程所占用的CPU时间  
system 从系统启动开始累计到当前时刻，处于核心态的运行时间  
idle 从系统启动开始累计到当前时刻，除IO等待时间以外的其它等待时间  
iowait 从系统启动开始累计到当前时刻，IO等待时间(since 2.5.41)  
irq 从系统启动开始累计到当前时刻，硬中断时间(since 2.6.0-test4)  
softirq 从系统启动开始累计到当前时刻，软中断时间(since 2.6.0-test4)  
stealstolen which is the time spent in other operating systems when running in a virtualized environment(since 2.6.11)  
guest which is the time spent running a virtual CPU for guest operating systems under the control of the Linux kernel(since 2.6.24)  
结论：总的cpu时间totalCpuTime = user + nice + system + idle + iowait + irq + softirq + stealstolen +guest  
[![screenshot](http://img4.tbcdn.cn/L1/461/1/894c2bc14d829d38d7139dc9e97351096627649d "screenshot")](http://img4.tbcdn.cn/L1/461/1/894c2bc14d829d38d7139dc9e97351096627649d)  
可以每1s获取一次CPU信息，分析整机CPU占用率。  
计算方法：  
1、 采样两个足够短的时间间隔的Cpu快照，分别记作t1,t2，其中t1、t2的结构均为：  
(user、nice、system、idle、iowait、irq、softirq、stealstolen、guest)的9元组;  
2、 计算总的Cpu时间片totalCpuTime  
a) 把第一次的所有cpu使用情况求和，得到s1;  
b) 把第二次的所有cpu使用情况求和，得到s2;  
c) s2 - s1得到这个时间间隔内的所有时间片，即totalCpuTime = j2 - j1 ;  
3、计算空闲时间idle  
idle对应第四列的数据，用第二次的idle - 第一次的idle即可  
idle=第二次的idle - 第一次的idle  
4、计算cpu使用率  
pcpu =100* (total-idle)/total

 

首先获取应用的进程id：  
adb shell ps | grep com.package | awk '{print $2}' &gt; tmp  
根据进程id，通过proc获取CPU信息  
while read line; do adb shell cat /proc/$line/stat | awk '{print $14,$15,$16,$17}' &gt;&gt; appcpu0; done &lt; tmp  
说明：以下只解释对我们计算Cpu使用率有用相关参数（14-17列）  
参数 解释  
pid 进程号  
utime 该任务在用户态运行的时间，单位为jiffies  
stime 该任务在核心态运行的时间，单位为jiffies  
cutime 所有已死线程在用户态运行的时间，单位为jiffies  
cstime 所有已死在核心态运行的时间，单位为jiffies

 

结论：进程的总Cpu时间processCpuTime = utime + stime + cutime + cstime，该值包括其所有线程的cpu时间。  
之后可以每1s获取一次CPU信息，分析获得app的CPU占用率等信息。