I was looking to determine(or count) the number of cores in the embedded processor of android device.
I tried using /proc/cpuinfo
, but it is not return
good thing is to use JNI, if possible in project
std::thread::hardware_concurrency()
Here you go (JAVA) :
try {
int ch, processorCount = 0;
Process process = Runtime.getRuntime().exec("cat /proc/cpuinfo");
StringBuilder sb = new StringBuilder();
while ((ch = process.getInputStream().read()) != -1)
sb.append((char) ch);
Pattern p = Pattern.compile("processor");
Matcher m = p.matcher(sb.toString());
while (processorCount.find())
processorCount++;
System.out.println(processorCount);
} catch (IOException e) {
e.printStackTrace();
}
You can try this method to get number of core.
private int getNumOfCores()
{
try
{
int i = new File("/sys/devices/system/cpu/").listFiles(new FileFilter()
{
public boolean accept(File params)
{
return Pattern.matches("cpu[0-9]", params.getName());
}
}).length;
return i;
}
catch (Exception e)
{
e.printstacktrace();
}
return 1;
}
Use this to get no. of cores.Do read this link very carefully and also see what the author is trying to tell between virtual device and a real device.
The code is referred from THIS SITE
/**
* 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;
}
}
Try this:
Runtime.getRuntime().availableProcessors();
This returns the number of CPU's available for THIS specific virtual machine, as I experienced. That may not be what you want, still, for a few purposes this is very handy. You can test this really easily: Kill all apps, run the above code. Open 10 very intensive apps, and then run the test again. Sure, this will only work on a multi cpu device, I guess.
Nice and simple solution in kotlin:
fun getCPUCoreNum(): Int {
val pattern = Pattern.compile("cpu[0-9]+")
return Math.max(
File("/sys/devices/system/cpu/")
.walk()
.maxDepth(1)
.count { pattern.matcher(it.name).matches() },
Runtime.getRuntime().availableProcessors()
)
}