How to get CPU usage statistics on Android?
Asked Answered
U

3

24

I want to get the overall CPU usage on Android, similar to what Windows' Task Manager does. I can parse the output of the top program included in Android, but if there is a API call that does the same thing, it would be better.

Any pointers?

Unqualified answered 18/3, 2010 at 4:46 Comment(0)
P
27

ATTENTION: This answer is old and does NOT work on newer versions of Android due to enhanced security mechanisms.

For complete CPU usage (not for each process) you can use:

    /**
 * 
 * @return integer Array with 4 elements: user, system, idle and other cpu
 *         usage in percentage.
 */
private int[] getCpuUsageStatistic() {

    String tempString = executeTop();

    tempString = tempString.replaceAll(",", "");
    tempString = tempString.replaceAll("User", "");
    tempString = tempString.replaceAll("System", "");
    tempString = tempString.replaceAll("IOW", "");
    tempString = tempString.replaceAll("IRQ", "");
    tempString = tempString.replaceAll("%", "");
    for (int i = 0; i < 10; i++) {
        tempString = tempString.replaceAll("  ", " ");
    }
    tempString = tempString.trim();
    String[] myString = tempString.split(" ");
    int[] cpuUsageAsInt = new int[myString.length];
    for (int i = 0; i < myString.length; i++) {
        myString[i] = myString[i].trim();
        cpuUsageAsInt[i] = Integer.parseInt(myString[i]);
    }
    return cpuUsageAsInt;
}

private String executeTop() {
    java.lang.Process p = null;
    BufferedReader in = null;
    String returnString = null;
    try {
        p = Runtime.getRuntime().exec("top -n 1");
        in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while (returnString == null || returnString.contentEquals("")) {
            returnString = in.readLine();
        }
    } catch (IOException e) {
        Log.e("executeTop", "error in getting first line of top");
        e.printStackTrace();
    } finally {
        try {
            in.close();
            p.destroy();
        } catch (IOException e) {
            Log.e("executeTop",
                    "error in closing and destroying top process");
            e.printStackTrace();
        }
    }
    return returnString;
}

Have fun with it :)

Profligate answered 22/4, 2012 at 16:14 Comment(7)
Not working. I am getting this error. Caused by: java.lang.NumberFormatException: For input string: "[?25l[0m[H[J[s[999C[999B[6n[uTasks:" On this line: cpuUsageAsInt[i] = Integer.parseInt(myString[i]);Pacorro
What about parsing top on your own and check how to modify these more than 6 year old snippet to make it great again? ;-)Profligate
Now top is only returning the the usage of my app. I don’t think it works as before it used to 6 years ago. :(Pacorro
That makes sense (I was wondering why the hack a user app is able to see the complete system cpu statistic). On which android version you tried it?Profligate
I tried it on Android 8.0 and 7.0. Both didn’t work. So is there a way to get that information anyway? I mean if I need to get only the CPU usage.Pacorro
@PronoyMukherjee, did you find a solution for this?Buyers
No not yet. I stopped trying for some different project.Pacorro
M
2

You can read /proc/stat and parse the file contents. The first line is like:
cpu 79242 0 74306 842486413 756859 6140 67701 0
The meanings of the columns are as follows, from left to right:

 - 1st column : user = normal processes executing in user mode
 - 2nd column : nice = niced processes executing in user mode
 - 3rd column : system = processes executing in kernel mode
 - 4th column : idle = twiddling thumbs
 - 5th column : iowait = waiting for I/O to complete
 - 6th column : irq = servicing interrupts
 - 7th column : softirq = servicing softirqs


Average idle percentage :
X % = ( idle * 100 ) / ( user + nice + system + idle + iowait + irq + softirq )
You can compute the difference in idle between time deltas, and figure CPU usage.

Marsiella answered 14/3, 2019 at 22:54 Comment(0)
E
1

You can reference the "DevTools" project.

Using ActivityManager you can get lots information, such as ActivityManager.RunningAppProcessInfo, ActivityManager.RunningTaskInfo, ...

But I am not sure the result will same as 'top' command.

see ActivityManager

Embed answered 18/3, 2010 at 7:10 Comment(5)
No CPU usage or time information can be found there (or did I miss it?), only memory usage among other things.Current
for CPU usage, you can refer CPUGauge.cpp, I think there is not "public API" for these kind of information you want. Or you have to parse "/proc/stat" by yourself.Embed
For reference, here is the source of CPUGauge android.googlesource.com/platform/frameworks/native/+/a6938ba/…Finegrain
What is "DevTools" project?Enscroll
Check this: android.googlesource.com/platform/prebuilts/devtools/+/masterEmbed

© 2022 - 2024 — McMap. All rights reserved.