1

我将如何确定有多少 CPU 在线?我有一个处理程序每​​ 1000 毫秒运行一次,读取当前频率,我还想确定有多少核心在线。

我一直在查看目录“/sys/devices/system/cpu/”。我监控了“/sys/devices/system/cpu/cpu1/online”,它始终为 1,我监控了 /cpu0/online,它也始终为 1。

此信息是内核/设备特定的吗?如何以适用于所有设备的方式找到在线的核心数量?

编辑: Runtime.availableProcessors() 似乎工作得很好,我仍然想知道是否有一个系统文件告诉你核心是否打开/关闭?

4

2 回答 2

1

我在我尝试过的设备上使用availableProcessors()取得了成功。官方 Java 文档中提供了对该函数的更详细描述。此论坛帖子中描述了另一种可能的解决方案。

于 2013-03-06T21:05:05.790 回答
-1
 /**
 * 
 * @return integer Array with 4 elements: user, system, idle and other cpu
 * usage in percentage. You can handle from here what you want. 
 * For example if you only want active CPUs add simple if statement >0 for usage
 */

private int[] getCpuUsageStatistic() {

String tempString = executeTop();

tempString = tempString.replaceAll(",", "");
tempString = tempString.replaceAll("User", "");
tempString = tempString.replaceAll("System", "");
tempString = tempString.replaceAll("IOW", "");
tempString = tempString.replaceAll("IRQ", "");
tempString = tempString.replaceAll("%", "");
for (int i = 0; i < 10; i++) {
    tempString = tempString.replaceAll("  ", " ");
}
tempString = tempString.trim();
String[] myString = tempString.split(" ");
int[] cpuUsageAsInt = new int[myString.length];
for (int i = 0; i < myString.length; i++) {
    myString[i] = myString[i].trim();
    cpuUsageAsInt[i] = Integer.parseInt(myString[i]);
}
return cpuUsageAsInt;
}

private String executeTop() {
java.lang.Process p = null;
BufferedReader in = null;
String returnString = null;
try {
    p = Runtime.getRuntime().exec("top -n 1");
    in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while (returnString == null || returnString.contentEquals("")) {
        returnString = in.readLine();
    }
} catch (IOException e) {
    Log.e("executeTop", "error in getting first line of top");
    e.printStackTrace();
} finally {
    try {
        in.close();
        p.destroy();
    } catch (IOException e) {
        Log.e("executeTop",
                "error in closing and destroying top process");
        e.printStackTrace();
    }
}
return returnString;
}
于 2013-03-06T21:18:53.063 回答