Tuesday, 23 March 2021

Measuring CPU load in an Android app using top

I am trying to collect CPU load information for an Android app using the top command. While the code below provides the expected output, the top interval should update its readings on intervals of (default) 3 seconds. Reading from the BufferedReader, each 3 seconds the same output is logged however. If I include the process's running time in top's output, it does not change either. So it looks like I just get the output of the first run each interval over and over.

Another thing I tried was having top just run once and collect just that output. While that works, it looks like the overhead of starting the top command distorts the readings.

I was also surprised I did not find readily available code for this. Is there a better way to check an app's CPU load now that access to the /proc directory has been restricted? The ps command also provides cpu load, but this provides a percentage of time spent running during the entire lifetime of a process, which is a less usable value.

private void startCollecting() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    ProcessBuilder builder = new ProcessBuilder("top", "-q", "-oCMDLINE,%CPU", "-s2", "-b");
                    Process process = builder.start();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        Log.d(TAG, line);
                        processStatsLine(line);
                    }
                    reader.close();
                    BufferedReader err_reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    while ((line = err_reader.readLine()) != null) {
                        Log.e(TAG, line);
                    }
                    process.waitFor();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }


from Measuring CPU load in an Android app using top

No comments:

Post a Comment