【问题标题】:How to Get CPU usage programmatically (With the cores frequency)如何以编程方式获取 CPU 使用率(使用核心频率)
【发布时间】:2019-06-26 19:14:58
【问题描述】:

我想了解(所有内核的)CPU 使用率

目前我无法获取“/proc/stat”的信息(自 API 27 起)

所以我想以频率或类似的频率获取信息:

使用所有以前的答案,我得到了我想要的,但还不够

主函数

  private fun ReadCpu3():String{

        val sb = StringBuffer();
        sb.append("abi: ").append(Build.CPU_ABI).append("\n");

        if (File("/proc/cpuinfo").exists()) {
            try {
                //val br =  BufferedReader(FileReader(File("/proc/cpuinfo")));
                val file = File("/proc/cpuinfo")

                file.bufferedReader().forEachLine {
                    sb.append(it+"\n");
                }

            } catch (e: IOException) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

我的结果


    processor       : 0
    vendor_id       : GenuineIntel
    cpu family      : 6
    model           : 45
    model name      : Intel(R) Xeon(R) CPU E5-2660 0 @ 2.20GHz
    stepping        : 6
    microcode       : 1561
    cpu MHz         : 600.000
    cache size      : 20480 KB
    physical id     : 0
    siblings        : 16
    core id         : 0
    cpu cores       : 8
    apicid          : 0
    initial apicid  : 0
    fpu             : yes
    fpu_exception   : yes
    cpuid level     : 13
    wp              : yes
    flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx lahf_lm ida arat epb pln pts dtherm tpr_shadow vnmi flexpriority ept vpid xsaveopt
    bogomips        : 4399.93
    clflush size    : 64
    cache_alignment : 64
    address sizes   : 46 bits physical, 48 bits virtual
    power management:

所以我得到了 CPU 的所有信息,但没有得到实际负载或使用情况。我不知道我是否可以通过当前信息来了解 cpu 使用情况以及准确程度。

【问题讨论】:

  • 当您想询问 kotlin 时,为什么要使用 java 标记。而且我认为 kotlin 遵循类似的命名约定:变量名应该以 camelCase 开头。大写用于类名。另请注意:垂直间距(空行)的目的是对事物进行分组。你不只是在这里或那里扔掉空行,因为你可以。想象一下,如果你的代码被编写出来会是什么感觉……就像你关心它一样?!
  • @GhostCat 谢谢你的建议,我更正了:)
  • @Divergence 但是我只想要 CPU 负载,而我在这个 awnser 中它返回一个完整的信息文本视图,你能告诉我我该怎么做才能获得 CPU 负载使用这段代码作为基础?
  • @WhySoBizarreCode 那么请附上它返回的示例。

标签: android kotlin


【解决方案1】:

您应该看到this SO post here。 基本上,您想使用RandomAccessFile 类来解析/proc/stat 文件。

编辑:上述解决方案不适用于 Android O 及更高版本。 See this link for more information。 Reddit 用户 fornwall 就此向 Google 提交了一份报告并得到:

状态:无法修复(预期行为)感谢您提交此错误 报告。

删除 /proc/stat 是故意的。 /proc/stat 泄漏端 关于应用程序的通道信息,这可能允许一个 应用程序来推断设备上其他应用程序的状态。 看 https://www.cl.cam.ac.uk/~lmrs2/publications/interrupts_pets16.pdf 例如。

EDIT2:我准备了一个示例(不使用 CpuStasCollector)

package com.k3.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    private static int sLastCpuCoreCount = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.txtv);
        textView.setText("");
        for (int i = 0; i < calcCpuCoreCount(); i++) {
            textView.append(takeCurrentCpuFreq(i) +"\n");
        }
    }

    private static int readIntegerFile(String filePath) {

        try {
            final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(filePath)), 1000);
            final String line = reader.readLine();
            reader.close();

            return Integer.parseInt(line);
        } catch (Exception e) {
            return 0;
        }
    }

    private static int takeCurrentCpuFreq(int coreIndex) {
        return readIntegerFile("/sys/devices/system/cpu/cpu" + coreIndex + "/cpufreq/scaling_cur_freq");
    }

    public static int calcCpuCoreCount() {

        if (sLastCpuCoreCount >= 1) {
            // キャッシュさせる
            return sLastCpuCoreCount;
        }

        try {
            // Get directory containing CPU info
            final File dir = new File("/sys/devices/system/cpu/");
            // Filter to only list the devices we care about
            final File[] files = dir.listFiles(new FileFilter() {

                public boolean accept(File pathname) {
                    //Check if filename is "cpu", followed by a single digit number
                    if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                        return true;
                    }
                    return false;
                }
            });

            // Return the number of cores (virtual CPU devices)
            sLastCpuCoreCount = files.length;

        } catch(Exception e) {
            sLastCpuCoreCount = Runtime.getRuntime().availableProcessors();
        }

        return sLastCpuCoreCount;
    }
}

【讨论】:

  • 出于安全原因,您不能在 andorid API27 或更高版本中使用 /proc/stat 文件。见stackoverflow.com/questions/52782894/…
  • 嗯,太好了。我会继续挖掘。
  • 但是有些应用程序会显示 cpu 使用情况,所以我认为他们正在使用频率或其他方式来实现这一点。
  • 他们运行 Android O+ 吗?
  • 我看到的所有其他针对 Android O+ 的 CPU 信息应用程序都使用库,我真的没有看到任何其他方式......
猜你喜欢
  • 1970-01-01
  • 2012-07-27
  • 2021-06-13
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多