在Android应用程序的跟踪长期CPU使用率 [英] Tracking long-term CPU usage of apps in android

查看:116
本文介绍了在Android应用程序的跟踪长期CPU使用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法,我可以,过一段说一个星期,看到每个应用程序有多少CPU使用?我能想到的唯一的办法就是反复解析顶出,但似乎并不像最有效的方式做到这一点。有没有更好的办法?

Is there any way that I can, over a period of say a week, see how much CPU each app uses? The only way that I can think of is to repeatedly parse top output but that doesn't seem like the most efficient way to do it. Is there a better way?

要添加一些情况下,基本上是手机本身的SDK traceview功能:的http://developer.android.com/guide/developing/debugging/debugging-tracing.html

To add some context, basically the traceview functionality of the SDK on the phone itself: http://developer.android.com/guide/developing/debugging/debugging-tracing.html

推荐答案

您可以使用的调试类监视进程

You can use the Debug class to monitor the processes

或使用该功能来计算CPU使用率

or use this function to calculate CPU usage

使用的/ proc / STAT / 总CPU使用率(适用于所有的CPU)。对于每个进程的使用

Use /proc/stat/ for the total CPU usage (for all CPU's) . For per process usage

private float readCpuUsage(int pid) {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/" + pid + "/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" ");

        long idle1 = Long.parseLong(toks[5]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" ");

        long idle2 = Long.parseLong(toks[5]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
} 

<分> source

要获得正在运行的进程列表

To get the list of running processes

ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> allTasks = mgr.getRunningTasks(showLimit);
/* Loop through all tasks returned. */
for (ActivityManager.RunningTaskInfo aTask : allTasks) 
{                  
    Log.i("MyApp", "Task: " + aTask.baseActivity.getClassName()); 
}

这篇关于在Android应用程序的跟踪长期CPU使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆