java - 应用程序如何测量 CPU 使用率(以百分比表示)?

标签 java android cpu-usage

所以我正在尝试编写一个应用程序来测量 CPU 使用情况(即 CPU 工作的时间与不工作的时间)。我做了一些研究,但不幸的是,对于如何完成有很多不同的意见。

这些不同的解决方案包括但不限于: Get Memory Usage in Android

http://juliano.info/en/Blog:Memory_Leak/Understanding_the_Linux_load_average

我尝试自己编写一些代码,但我认为可能会成功,因为上面的链接不会考虑核心关闭时的情况(或者是吗?)

    long[][] cpuUseVal = {{2147483647, 0} , {2147483647, 0} , {2147483647, 0} , 
        {2147483647, 0} , {2147483647, 0}};

    public float[] readCPUUsage(int coreNum) {
    int j=1;
    String[] entries;  //Array to hold entries in the /proc/stat file
    int cpu_work;
    float percents[] = new float[5];
    Calendar c = Calendar.getInstance();

    // Write the dataPackage
    long currentTime = c.getTime().getTime();

        for (int i = 0; i <= coreNum; i++){
    try {     
            //Point the app to the file where CPU values are located
            RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
            String load = reader.readLine();
            while (j <= i){
                load = reader.readLine();
                j++;
            }
            //Reset j for use later in the loop
            j=1; 

            entries = load.split("[ ]+");

            //Pull the CPU working time from the file
            cpu_work = Integer.parseInt(entries[1]) + Integer.parseInt(entries[2]) + Integer.parseInt(entries[3])
                      + Integer.parseInt(entries[6]) + Integer.parseInt(entries[6]) + Integer.parseInt(entries[7]);
            reader.close();

            percents[i] = (float)(cpu_work - cpuUseVal[i][1]) / (currentTime - cpuUseVal[i][0]);

            cpuUseVal[i][0] = currentTime;
            cpuUseVal[i][1] = cpu_work;

    //In case of an error, print a stack trace   
    } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    //Return the array holding the usage values for the CPU, and all cores
    return percents;
}

所以这是我编写的代码的想法...我有一个全局数组,其中包含一些虚拟值,这些虚拟值应在函数第一次运行时返回负百分比。这些值存储在数据库中,因此我知道忽略任何负面信息。不管怎样,函数运行,获取 cpu 执行某些操作的时间值,并将其与函数上次运行的时间进行比较(在全局数组的帮助下)。这些值除以函数运行之间耗时量(借助日历)

我已经下载了一些现有的 CPU 使用情况监视器,并将它们与我从我的应用程序中获得的值进行了比较,而我的值与他们获得的值相差甚远。有人可以解释一下我做错了什么吗?

感谢一些帮助,我已将我的函数更改为如下所示,希望这可以帮助有此问题的其他人

    // Function to read values from /proc/stat and do computations to compute CPU %
public float[] readCPUUsage(int coreNum) {
    int j = 1;
    String[] entries; 
    int cpu_total;
    int cpu_work;
    float percents[] = new float[5];

    for (int i = 0; i <= coreNum; i++) {
        try {
            // Point the app to the file where CPU values are located
            RandomAccessFile reader = new RandomAccessFile("/proc/stat","r");
            String load = reader.readLine();
            // Loop to read down to the line that corresponds to the core
            // whose values we are trying to read
            while (j <= i) {
                load = reader.readLine();
                j++;
            }
            // Reset j for use later in the loop
            j = 1;
            // Break the line into separate array elements. The end of each
            // element is determined by any number of spaces
            entries = load.split("[ ]+");

            // Pull the CPU total time on and "working time" from the file
            cpu_total = Integer.parseInt(entries[1])
                    + Integer.parseInt(entries[2])
                    + Integer.parseInt(entries[3])
                    + Integer.parseInt(entries[4])
                    + Integer.parseInt(entries[5])
                    + Integer.parseInt(entries[6])
                    + Integer.parseInt(entries[7]);
            cpu_work = Integer.parseInt(entries[1])
                    + Integer.parseInt(entries[2])
                    + Integer.parseInt(entries[3])
                    + Integer.parseInt(entries[6])
                    + Integer.parseInt(entries[7]);
            reader.close();

            //If it was off the whole time, say 0
            if ((cpu_total - cpuUseVal[i][0]) == 0)
                percents[i] = 0;
            //If it was on for any amount of time, compute the %
            else
                percents[i] = (float) (cpu_work - cpuUseVal[i][1])
                        / (cpu_total - cpuUseVal[i][0]);

            //Save the values measured for future comparison
            cpuUseVal[i][0] = cpu_total;
            cpuUseVal[i][1] = cpu_work;

            // In case of an error, print a stack trace
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    // Return the array holding the usage values for the CPU, and all cores
    return percents;
}

最佳答案

应用程序不会测量 CPU 使用率,而是内核通过每秒中断进程 100 次(或其他频率,具体取决于内核的调整方式)并递增与中断时正在执行的操作相对应的计数器来测量 CPU 使用率。

如果在此过程中 => 增加用户计数器。

如果在内核中=>增加系统计数器

如果等待磁盘、网络或设备 => 增加等待 IO

否则增加空闲计数器。

正常运行时间由运行队列的平均长度衰减决定,即有多少线程正在等待运行。第一个数字是最后一分钟的平均长度。您可以通过JMX获取平均负载。

关于java - 应用程序如何测量 CPU 使用率(以百分比表示)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21535436/

相关文章:

r - R 仍然是单线程的吗?

elasticsearch cpu占用率高

android - 在前台启动两个服务?

android - AppCompatActivity 的 TextView 颜色始终为白色

java - 持久化时间戳类型只有日期没有时间

java - 无需浏览器即可解释 html 输出

android - 从 Jenkins 管道中的 build.gradle 中读取 android 的版本名称

Python socketserver向多个客户端发送数据cpu使用率高

java - 已在 tomcat 中部署 2 个应用程序时出现邮件问题

java - 由 : java. lang.ClassNotFoundException : org. eclipse.core.runtime.Plugin 引起