如何检查Android操作系统确实使用多核

时间:2013-12-08 10:25:51

标签: android

我们都知道Android OS支持多核心架构。但是如何测试线程实际上是在多个内核上进行处理的呢?它是一个项目分配。请建议如何继续。

2 个答案:

答案 0 :(得分:1)

try this.Might help you

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());
        //Return the number of cores (virtual CPU devices)
        return files.length;
    } catch(Exception e) {
        //Default to return 1 core
        return 1;
    }
}

答案 1 :(得分:0)

尝试parsing /proc/cpuinfo,例如使用Guava's Files helper来读取文件:

public int numCores() throws IOException {
    Pattern processorLinePattern = Pattern.compile("^processor\\s+: \\d+$", Pattern.MULTILINE);
    String cpuinfo = Files.toString(new File("/proc/cpuinfo"), Charsets.US_ASCII);
    Matcher matcher = processorLinePattern.matcher(cpuinfo);
    int count = 0;
    while (matcher.find()) {
        count++;
    }
    return count;
}

您通常更喜欢使用Guava或Apache Commons等帮助程序库进行I / O操作,有许多边缘情况可以解决。如果你需要避免依赖,请自己实现类似的东西(这个示例实现中有几个漏洞,但它并不太可怕):

private String readFile(File file, Charset charset) throws IOException {
    StringBuilder result = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line).append("\n");
        }
        return result.toString();
    } finally {
        reader.close();
    }
}

public int numCores() throws IOException {
    // ...
    String cpuinfo = readFile(new File("/proc/cpuinfo"), Charset.forName("US-ASCII"));
    // ...
}