CPU进程占用率和线程占用率计算:

思路如下:

1.通过读取 /proc/stat 文件获取总的 CPU 时间,

2.读取 /proc/[PID]/stat 获取进程 CPU 时间,

3.读取 /proc/[PID]/task/[TID]/stat 获取线程 CPU 时间。

4.采样两个足够短的时间间隔的 CPU 快照与进程或线程快照来计算其 CPU 使用率。

/**读取的文件位置            // 含义

* /proc/stat                        // 总的cpu时间

* /proc/[pid]/stat                // 进程CPU使用情况

* /proc/[pid]/task/[tid]/stat  // 进程下面各个线程的CPU使用情况

* /proc/[pid]/sched            // 进程CPU调度相关

* /proc/loadavg                 // 系统平均负载,uptime命令对应文件

*/

参数细节详细参考:http://www.samirchen.com/linux-cpu-performance/

https://man7.org/linux/man-pages/man5/proc.5.html

//    user(223447) 从系统启动开始累积到当前时刻,处于用户态的运行时间,不包含 nice 值为负的进程。

//    nice(240) 从系统启动开始累积到当前时刻,nice 值为负的进程所占用的 CPU 时间。

//    system(4504182) 从系统启动开始累积到当前时刻,处于核心态的运行时间。

//    idle(410802165) 从系统启动开始累积到当前时刻,除 IO 等待时间以外的其他等待时间。

//    iowait(59753) 从系统启动开始累积到当前时刻,IO 等待时间。(since 2.5.41)

//    irq(412) 从系统启动开始累积到当前时刻,硬中断时间。(since 2.6.0-test4)

//    softirq(586209) 从系统启动开始累积到当前时刻,软中断时间。(since 2.6.0-test4)

//    stealstolen(0) Which is the time spent in other operating systems when running in a virtualized environment.(since 2.6.11)

//    guest(0) Which is the time spent running a virtual CPU for guest operating systems under the control of the Linux kernel.(since 2.6.24)
 

最终效果:

如何使用android studio监测cpu使用率 安卓cpu使用率监控_等待时间

不足之处是:从Android 8,26开始,如果不是系统应用,就不能读取 /proc/stat了,所以使用process = Runtime.getRuntime().exec("top -n 1")这种方式获取的,和读取proc方式相比,还是有点问题的,

1.速度:读取proc的方式明显快于shell方式。后一种方式返回所以的占用,并且分两次,存在一个时间差,导致输出的结果不是同一时刻的进程占用和线程占用。

2.精确性:shell方式,虽然直接返回占用率,只需要简单粗暴的解析字符不用计算就能得到占用,但是没有之前方式精确。

谷歌添加的这个限制是挺蛋疼的,虽然是出于安全考虑。兼容Android O以上的版本用shell方式也是无奈之举,查了很多质料,暂时是找不到更好的方法,就先这样叭。

工作中柳汽项目用到的车机为Android 6,可以较好的得到CPU占用率结果。

项目地址:https://github.com/Ulez/CpuTracer