0

I want a method to get the current overall cpu usage in android! I used a method that I found in this site and it's stated below.

private float readUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/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;
} 

But this method only returns me one float value. what I need is the current usage statistics like the percentage used by the system, and the percentage used by the user! can any one help me with this. a tutorial would be nice, but if any one is generous enough to give me a good code It would be my pleasure!

thank you!

Imesh Chandrasiri
  • 5,558
  • 15
  • 60
  • 103

2 Answers2

0

From the linux proc manual page:

/proc/stat kernel/system statistics. Varies with architecture. Common entries include:

          cpu  3357 0 4313 1362393
                 The   amount  of  time,  measured  in  units  of  USER_HZ
                 (1/100ths  of  a  second  on  most   architectures,   use
                 sysconf(_SC_CLK_TCK) to obtain the right value), that the
                 system spent in user mode, user mode  with  low  priority
                 (nice),  system  mode,  and  the idle task, respectively.
                 The last value should be USER_HZ times the  second  entry
                 in the uptime pseudo-file.

You may also want to look at the source of 'top' in AOSP platform/system/core/toolbox

Chris Stratton
  • 39,853
  • 6
  • 84
  • 117
0

When you are looking at the statistics in "proc/stat"

  • it will provide you with the overall CPU Usage (Kernal Mode+ User Mode)
  • you can only get the CPU USAGE in terms of system & user mode per process proc/[pid]/stat - 14th param :- user mode in jiffies - 15th param :- kernal mode in jiffies
  • calculate the Kernel Mode Usage for all the processes/pids and can consider it as system CPU usage...
mn0102
  • 839
  • 1
  • 12
  • 25