我正在尝试编写一个小代码,用于转储我的Android应用程序的CPU利用率(在过去10秒内使用的cpu百分比,每10秒转储一次)。
现在假设手机中有2个或4个核心。如何有效地转储应用程序使用的%cpu。我搜索了一些top命令的样本,但我不确定如何使用top命令的数字来显示跨多核和最近10秒的CPU利用率。
我添加了以下代码:但buf. exec
使用ls
命令返回有效结果时始终为空,但top
没有。我需要在mainfest中获得一些权限来执行top命令......
String str = new String();
str = "top -l1";
Process p;
p = Runtime.getRuntime().exec(str);
BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
/* Skip 6 lines */
int count = 0;
char[] buf= new char[10240];
bri.read(buf);
Log.e("TEST", new String(buf));
答案 0 :(得分:0)
我对top
不太熟悉,但this question似乎暗示有一种方法可以从各个核心收集数据。
在任何情况下,我建议您使用Dumpsys tool代替,这更有趣,因为它可以为您提供CPU利用率,而不管核心数量。例如,命令:
adb shell dumpsys cpuinfo
将提供表格的输出:
Load: 0.08 / 0.4 / 0.64
CPU usage from 42816ms to 34683ms ago:
system_server: 1% = 1% user + 0% kernel / faults: 16 minor
kdebuglog.sh: 0% = 0% user + 0% kernel / faults: 160 minor
tiwlan_wq: 0% = 0% user + 0% kernel
usb_mass_storag: 0% = 0% user + 0% kernel
pvr_workqueue: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
TOTAL: 6% = 1% user + 3% kernel + 0% irq
查看此SO答案,了解有关如何使用Dumpsys的更多详细信息:What's the Android ADB shell "dumpsys" tool and what are its benefits?
答案 1 :(得分:0)
对于任何达成此问题的人来解决这个问题,我发布了关于如何从" top"获取cpu使用价值的解决方案。命令
private String getCpuUsage()
{
ArrayList<String> list = new ArrayList<String>();
String cpuUsageValue = "";
Process p = null;
try {
p = Runtime.getRuntime().exec(new String[] { "sh", "-c", "top -n 1 | grep " + appProcessName }); //appProcessName is com.example.app
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
int i =0;
String line = "";
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//while(line != null)
if(line != null)
{
//11203 0 0% S 13 901560K 43528K fg u0_a141 com.example.app
String lineOuput[] = line.split(" ");
cpuUsageValue = lineOuput[5].trim();
//[19472, , 0, , , 0%, S, , , , 15, 904664K, , 44148K, , fg, u0_a141, , com.example.app]
Log.i(TAG, "cpu usage value : " + cpuUsageValue);
list.add(line);
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
else
{
Log.i(TAG, "command line is null");
}
return cpuUsageValue;
}