首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android设备是不是双核,有什么API可以判断吗?

Android设备是不是双核,有什么API可以判断吗?
EN

Stack Overflow用户
提问于 2011-09-29 13:28:19
回答 2查看 1.4K关注 0票数 3

我正在通过多线程进行双核优化,它的工作原理是这样的:如果设备有双核处理器,则创建两个线程来执行计算,如果设备只有单核处理器,则只创建一个线程来执行计算。

我的问题是:我的程序如何知道设备是否是双核的?我只想有一个既能在双核设备上运行又能在单核设备上运行的程序,所以它必须能够知道这些信息。

代码如下:

代码语言:javascript
复制
    if( xxx_API_is_device_dual_core() )  // Inside if() is the expected API
    {
     saveThread = new SaveThread[2];
    }
    else
    {
    saveThread = new SaveThread[1];
    }

非常感谢您的帮助!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-29 13:51:02

双核设备上的Runtime.availableProcessors()是否无法正确报告?

票数 2
EN

Stack Overflow用户

发布于 2012-04-30 10:52:47

Runtime.availableProcessors()似乎并不适用于所有的安卓设备(例如,在我的双核Galaxy S II上,它只返回"1“)。物理CPU和虚拟CPU(又称核心)之间可能存在一些混淆。

我发现最可靠的方法是described in this forum post。基本上,您必须对/sys/ devices /system/ CPU /中的虚拟cpu设备进行计数。这将适用于无需修改的双核和四核设备。

我已经在我的Galaxy S II (2核)和Asus Transformer Prime (4核)上测试了这个方法,它报告正确。下面是一些示例代码(摘自my answer to this question):

代码语言:javascript
复制
/**
 * 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());
        //Return the number of cores (virtual CPU devices)
        return files.length;
    } catch(Exception e) {
        //Default to return 1 core
        return 1;
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7592843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档