Skip to content

Instantly share code, notes, and snippets.

@fredgrott
Created May 25, 2012 08:56
Show Gist options
  • Save fredgrott/2786791 to your computer and use it in GitHub Desktop.
Save fredgrott/2786791 to your computer and use it in GitHub Desktop.
NumCpuCores
package org.bitbucket.fredgrott.gwsdroidlive.app;
import java.io.File;
import java.io.FileFilter;
import java.util.regex.Pattern;
public class NumCPUCores {
/** The device cpu num cores. */
public static int deviceCPUNumCores;
/**
* 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
*/
public static int getDeviceCPUNumCores() {
//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 deviceCPUNumCores = files.length;
} catch(Exception e) {
//Default to return 1 core
return deviceCPUNumCores = 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment