Reputation: 53
How would i go about determining how many cpu's are online? I have a handler running every 1000 ms reading the current frequency and i also want to determine how many cores are online.
I've been looking through the directory "/sys/devices/system/cpu/". I've monitored "/sys/devices/system/cpu/cpu1/online" which is always 1, i've monitored /cpu0/online which is also always 1.
Is this information kernel/device specific? How can i find how many cores are online in a way that works on all devices?
edit: Runtime.availableProcessors() seems to work nicely, i'm still interested in knowing if there is a system file that tells you if a core is on/off?
Upvotes: 1
Views: 490
Reputation: 6517
/**
*
* @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;
}
Upvotes: -1
Reputation: 1345
I have success with availableProcessors() on the devices I have tried. A more detailed description of the function is available in the official Java doc. Another possible solution is described in this forum post.
Upvotes: 1