Android read CPU time in states for multicore devi

2019-07-28 23:27发布

I'm trying to have my app show time spent by the CPU at each frequency. The main issue is when a CPU goes offline (due to hotplugging or deep sleep) the file /CPUN/cpufreq/stats/time_in_state gets removed and times reset to all 0s.

So this limits me to only be able to show the times on CPU 0.

What I've Tried

  • Use FileObserver service to monitor the creation/deletion of the file This should work in theory but for whatever reason when the device goes into deep sleep it fails to report the deleting of those files. Same for when waking, the files must be created before the FileObserver is able to resume monitoring.

So short of a wakelock, is it at all possible to monitor the times from those CPUs that go offline, clearing time_in_state files?

1条回答
萌系小妹纸
2楼-- · 2019-07-28 23:40

Try this:

String path = "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state"; // CPU0
String path1 = "/sys/devices/system/cpu/cpu1/cpufreq/stats/time_in_state"; // CPU1
String path2 = "/sys/devices/system/cpu/cpu2/cpufreq/stats/time_in_state"; // CPU2
String path3 = "/sys/devices/system/cpu/cpu3/cpufreq/stats/time_in_state"; // CPU3
//...
InputStream states = new FileInputStream(path);
InputStreamReader reader = new InputStreamReader(states);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = "";
 while ((line = bufferedReader.readLine()) != null) {
      System.out.println("RESULT: " + line);
}

You can use a for loop to get all CPUs. To get Number of available use:
int cores = Runtime.getRuntime().availableProcessors()

So the for goes from 0 to cores - 1

查看更多
登录 后发表回答