如何通过应用程序获取内存使用和CPU使用?

时间:2012-03-18 05:52:50

标签: android memory process cpu-usage

我发现此代码可以获得整体cpu使用率。这是否可以将其转换为通过进程告诉cpu使用情况?是否有任何API可以让我们获得android的CPU或内存使用?

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;
}

4 个答案:

答案 0 :(得分:4)

Context context = this.getApplicationContext();
ActivityManager mgr = (ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> processes = mgr.getRunningAppProcesses();
Log.e("DEBUG", "Running processes:");
for(Iterator i = processes.iterator(); i.hasNext(); )
{
    RunningAppProcessInfo p = (RunningAppProcessInfo)i.next();
    Log.e("DEBUG", "  process name: "+p.processName);
    Log.e("DEBUG", "     pid: "+p.pid);                    
    int[] pids = new int[1];
    pids[0] = p.pid;
    android.os.Debug.MemoryInfo[] MI = mgr.getProcessMemoryInfo(pids);
    Log.e("memory","     dalvik private: " + MI[0].dalvikPrivateDirty);
    Log.e("memory","     dalvik shared: " + MI[0].dalvikSharedDirty);
    Log.e("memory","     dalvik pss: " + MI[0].dalvikPss);            
    Log.e("memory","     native private: " + MI[0].nativePrivateDirty);
    Log.e("memory","     native shared: " + MI[0].nativeSharedDirty);
    Log.e("memory","     native pss: " + MI[0].nativePss);            
    Log.e("memory","     other private: " + MI[0].otherPrivateDirty);
    Log.e("memory","     other shared: " + MI[0].otherSharedDirty);
    Log.e("memory","     other pss: " + MI[0].otherPss);

    Log.e("memory","     total private dirty memory (KB): " + MI[0].getTotalPrivateDirty());
    Log.e("memory","     total shared (KB): " + MI[0].getTotalSharedDirty());
    Log.e("memory","     total pss: " + MI[0].getTotalPss());            
}
  • 在现代操作系统中,app使用共享库。因此,使用了一些存储器 通过多个应用程序,确定应用程序内存使用情况变得复杂。

  • dalvikPrivateDirty是将由java释放的内存 如果进程被终止,则为虚拟机

  • nativePrivateDirty与本机代码相同,对于某些人来说是相同的 其他代码(不知道还有什么)
  • otherPrivateDirty dalvikSharedDirty是使用的共享内存 java虚拟机但是这不会被释放

  • 如果这个应用程序被杀死dalvikPss - 估计内存是多少 应用程序使用。这包括所有私人记忆和一个
    共享内存的一部分检查pss&gt; = private原因
    只使用一小部分共享内存是为了这样 所有负责任的应用程序共享内存使用的合理性

此值用于估计应用的内存负载。

总数是dalvik,native和其他的总和。

答案 1 :(得分:2)

读/ proc / [pid] / stat - [pid]是你的目标进程的pid

然后寻找以下成员。

  • utime%lu
  • stime%lu

man / proc @ http://linux.die.net/man/5/proc

答案 2 :(得分:0)

试试这个:

    private float getCpuPer() { //for single process

    float cpuPer = 0;
    try {
        String[] cmd = {"top", "-n", "1"};
        Process process = Runtime.getRuntime().exec(cmd);
        BufferedReader stdInput = new BufferedReader(new
                InputStreamReader(process.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
                InputStreamReader(process.getErrorStream()));

        // read the output from the command
        //System.out.println("Here is the standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            if (s.contains("your process name")) {
                String [] arr = s.split(" ");
                for (int i = 0; i < arr.length; i++) {
                    if (arr[i].contains("%")) {
                        s = arr[i].replace("%", "");
                        cpuPer = Float.parseFloat(s);
                        break;
                    }
                }
                //System.out.println(s);
            }
        }

        // read any errors from the attempted command
        //System.out.println("Here is the standard error of the command (if any):\n");
        //while ((s = stdError.readLine()) != null) {
            //System.out.println(s);
        //}
    } catch (IOException e) {
        e.printStackTrace();
    }
    return cpuPer;
}

答案 3 :(得分:-2)

运行应用程序时,运行Android-sdk \ tools文件夹中的DDMS工具。您将在哪里获得有关所有运行过程的完整详细信息。如果您启用了调试功能的Android设备,那么您甚至可以通过将其连接到系统来调试设备。