While developing the latest release of Micro CPU Monitor, I ran into difficulties trying to determine the number of cores in a mobile device. In the past I’d been using /proc/stat to get CPU usage for the whole system (all processors and cores combined). After reading this article (including the comments) and playing around a bit in bash, I discovered this same file could also be used to get CPU usage for each processor/core separately.
But it turns out that a lot of multi-core Android devices actually switch the cores on and off independently, in order to save power. On my dual core Galaxy S II, /proc/stat will sometimes only show CPU usage for a single core. At other times, it will show both cores. So this makes it pretty much impossible to use /proc/stat to calculate a reliable figure for the number of cores.
After a lot more fiddling (and thanks to the feedback of several devs on Google+) I managed to come up with a solution. To count the number of cores, I just needed to enumerate the CPU devices in /sys/devices/system/cpu/. From my research, it seems that this directory is readable from any Android app - even without root.
Here’s a simple function which uses this method to return the total number of CPU cores for the system. On a desktop OS there could be some confusion between physical and virtual CPUs, but on Android it’s pretty simple. At this stage, there are only really dual-core and quad-core devices out there, so we can get an accurate figure just by counting the virtual devices like this.
[java]
/**
-
Gets the number of cores available in this device, across all processors.
-
Requires: Ability to peruse the filesystem at “/sys/devices/system/cpu”
-
@return The number of cores, or 1 if failed to get result
*/
private int getNumCores() {
//Private Class to display only CPU devices in the directory listing
class CpuFilter implements FileFilter {
@Override
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;
}
}try {
//Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
//Filter to only list the devices we care about
File[] files = dir.listFiles(new CpuFilter());
Log.d(TAG, "CPU Count: "+files.length);
//Return the number of cores (virtual CPU devices)
return files.length;
} catch(Exception e) {
//Print exception
Log.d(TAG, “CPU Count: Failed.”);
e.printStackTrace();
//Default to return 1 core
return 1;
}
}
[/java]
I hope this code will be helpful for any other devs out there who are in a similar situation. I’d definitely welcome any feedback as well - if you’ve got a different approach or some comments, I’d be happy to hear them!
Now… back to my coding