獲取CPU總數(shù)
public static 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());
//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;
}
}
獲取可用的CPU數(shù)
一些設(shè)備根據(jù)系統(tǒng)負(fù)載已經(jīng)關(guān)閉一個(gè)或多個(gè)內(nèi)核的cpu脐雪,對(duì)于這些設(shè)備蛉幸,availableProcessors()返回的是可用的內(nèi)核數(shù)班套,這個(gè)數(shù)字一般小于內(nèi)核總數(shù):
public static int getNumAvailableCores() {
return Runtime.getRuntime().availableProcessors();
}