【问题标题】:Is there any API that tells whether an Android device is dual-core or not?是否有任何 API 可以判断 Android 设备是否为双核?
【发布时间】:2011-09-29 05:28:19
【问题描述】:

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

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

这样的代码:

    if( xxx_API_is_device_dual_core() )  // Inside if() is the expected API
    {
     saveThread = new SaveThread[2];
    }
    else
    {
    saveThread = new SaveThread[1];
    }

非常感谢您的帮助!

【问题讨论】:

    标签: android


    【解决方案1】:

    Runtime.availableProcessors() 似乎不适用于所有 Android 设备(例如,它在我的双核 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):

    /**
     * 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;
        }
    }
    

    【讨论】:

    • 我会将Runtime.availableProcessors() 作为默认返回值。
    【解决方案2】:

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

    【讨论】:

    • 哇,这个 API 好像是我需要的!我会在一分钟内检查它,让你看看它是否有效。
    • Runtime.availableProcessors() 为双核设备返回 2,这正是我所期望的。谢谢丹尼斯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多