【问题标题】:How to get the number of cores of an android device如何获取android设备的核心数
【发布时间】:2015-05-08 08:49:31
【问题描述】:

我正在寻找确定(或计算)android 设备嵌入式处理器中的内核数量。

我尝试使用/proc/cpuinfo,但它没有返回设备的核心数!

我在 Internet 上的任何地方都没有找到代码。这里有没有人知道我该如何确定这一点,然后请回答。提前致谢

更新:

这个问题的答案How can you detect a dual-core cpu on an Android device from code? 在某些设备上运行不佳。我测试它们是双核和四核处理器,它们分别返回 2 和 4,很好!

但是,在像三星 Note 3 这样的 Octa Core 处理器上,它返回 4。 (也许在注释 3 中有 2 组四核处理器单独运行

我想解决这个问题。

更新

应用程序 CPU-Z 在我的设备 Samsung note 3 中返回正确的核心数 这里似乎有一个可能的解决方案......

【问题讨论】:

  • 请解释否决票
  • 你需要有root权限,你想要root设备的解决方案吗?
  • 请看我的编辑,我已经详细解释了问题!!!
  • 我认为它应该在三星 note 3 上返回 4。你不能同时使用所有 8 个,反正它不是真正的八核。只是三星销售更多垃圾的方式。解释一下,它有 4 个运行 1,9GHz 的内核和 4 个运行 1,3GHz 的内核。当时只有 4 个处于活动状态,具体取决于笔记当前正在执行的处理量以及您使用的函数,返回最大活动核心数,因为大多数人使用该数字作为线程池大小的数量
  • CPU-Z 仅依赖于显示 8 的外部数据库(营销废话)。它不询问系统本身(一次最多有 4 个内核)。

标签: android


【解决方案1】:

您可以将上述答案与此答案结合使用。这样它会在运行 API 17+ 的设备上执行得更快,因为这种方法比过滤掉文件要快得多。

private int getNumberOfCores() {
    if(Build.VERSION.SDK_INT >= 17) {
        return Runtime.getRuntime().availableProcessors()
    }
    else {
       // Use saurabh64's answer
       return getNumCoresOldPhones();
    }
}

/**
 * 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 getNumCoresOldPhones() {
    //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;
    }
}

public int availableProcessors ()

在 API 级别 1 中添加 返回可用的处理器内核数 到 VM,至少 1。传统上这返回数字 目前在线,但许多移动设备都可以使用未使用的 核心离线以节省电力,因此发布比 Android 4.2 (Jelly) 更新的版本 Bean) 返回可以使用的最大内核数 如果没有功率或热量限制。

还有关于位于的文件中的核心数量的信息 /sys/devices/system/cpu/present 它以以下格式报告可用 CPU 的数量:

  • 0 -> 单 CPU/内核
  • 0-1 -> 两个 CPU/内核
  • 0-3 -> 四个 CPU/内核
  • 0-7 -> 八个 CPU/内核

等等

另外,请检查注释 3 中 /sys/devices/system/cpu/possible 的内容

这两个文件都设置了r--r--r--444 文件权限,因此您应该能够在代码中没有root 设备的情况下读取它们。

编辑:发布代码来帮助你

 private void printNumberOfCores() {
        printFile("/sys/devices/system/cpu/present");
        printFile("/sys/devices/system/cpu/possible");

    }

    private void printFile(String path) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(path);
            if (inputStream != null) {

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line;

                do {
                    line = bufferedReader.readLine();
                    Log.d(path, line);
                } while (line != null);
            }
        } catch (Exception e) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

结果

D//sys/devices/system/cpu/present﹕ 0-3
D//sys/devices/system/cpu/possible﹕ 0-3

测试是在运行 BlissPop ROM 和 Android v5.1.1 的 OnePlus One 上运行的,它可以正常打印。请尝试使用您的三星

【讨论】:

  • Runtime.getRuntime().availableProcessors() 仍然返回 4 而不是 8
  • 你为什么要在这里改变你的评论,正如你在问题下的 cmets 中所说的那样,我非常了解这类手机的现实情况。
  • 必须有一种方法可以找到总核心数,而不管它们的行为如何,顺便说一句,我尝试在多任务处理和玩重型游戏时运行该应用程序,但它仍然返回 4
  • @VivekWarde 我已经对我的帖子进行了编辑,您能检查一下这两个文件中的内容吗?
  • 好的,现在使用...cpu/present...cpu/possibleFile[] files 内生成Null。很抱歉,但你的最后一部分也没有用
【解决方案2】:

首先,这似乎是不可能的,这里有一些信息:

我们将使用三星 Exynos 5 Octa CPU 作为此线程的示例,但通常任何 ARM 处理器都可以正常工作。

三星 Exynos 5 Octa CPU 有 8 个 CPU 内核。但实际上它有两个进程,每个进程有 4 个内核。这称为 big.LITTLE。您有 1 个快速处理器和 1 个节能处理器。

在 Exynos 5 CPU 中,它内置了两个不同的 CPU,一个 Cortex a15 和一个 Cortex a7...

在 big.LITTLE 内,两个 CPU 不能同时运行,在任何给定时间只能有一个 CPU 处于活动状态......

但是还有一个叫做“big.LITTLE mp”的东西,其中两个 CPU 可以同时处于活动状态,但这里有一个问题(再次!)在任何给定时间,只有四个内核可以对软件处于活动状态。这里有一张图片可以更好地解释这一点:

现在您可以看到,这里更强大的处理器使用单个 CPU 内核,然后其他四个内核从更节能的 a7 CPU 集群中激活。

您可以在此处阅读有关 big.LITTLE 架构的更多信息: http://www.arm.com/products/processors/technologies/biglittleprocessing.php

您可以在此处阅读有关 big.LITTLE mp 架构的更多信息: http://www.arm.com/products/processors/technologies/biglittleprocessing.php

你现在想知道的是,是否有可能知道 CPU 架构是 Big.LITTLE 还是 BIG.LITTLE mp。然后看看是否可以直接从每个单独的 CPU 中找出 CPU 计数,但我找不到任何相关代码。 ARMs 网站上有很多文档,但我不太确定是否可以获得这些信息。不过,无论哪种方式,只能使用 4 个 CPU 内核,因此您拥有的代码在技术上是正确的,因为这是可用内核的数量。

我希望这对您有所帮助,如果您有任何问题或想要解决任何问题,请告诉我。那里有很多信息

【讨论】:

  • 感谢您让问题更清楚。但是应用程序 CPU-Z 正在做我想做的事。看我的截图,我编辑了问题
  • CPU-Z 可能正在查看模型信息并从在线资源中提取其余数据。今晚我会进一步看看。可悲的是,我没有可以测试的手机,所以会很困难。
  • 是的,我也有可能返回关键字octa, , quad, or dual`,就像这样
  • 正确,这始终是一个选项。通过电子邮件向 CPU-Z 支持发送电子邮件总是有效的,他们可能会提供帮助!
  • @VivekWarde 如果你真的对 cpu-z 这么感兴趣,何不尝试反编译一下看看是怎么回事?
【解决方案3】:

试试这个:

Runtime.getRuntime().availableProcessors();

根据我的经验,这将返回可用于此特定虚拟机的 CPU 数量。这可能不是您想要的,但出于某些目的,这非常方便。你可以很容易地对此进行测试:杀死所有应用程序,运行上面的代码。打开 10 个非常密集的应用程序,然后再次运行测试。当然,我猜这只适用于多 CPU 设备。

【讨论】:

    【解决方案4】:

    你可以试试这个方法来获取核心数。

     private int getNumOfCores()
          {
            try
            {
              int i = new File("/sys/devices/system/cpu/").listFiles(new FileFilter()
              {
                public boolean accept(File params)
                {
                  return Pattern.matches("cpu[0-9]", params.getName());
                }
              }).length;
              return i;
            }
            catch (Exception e)
            {
                  e.printstacktrace();
            }
            return 1;
          }
    

    【讨论】:

      【解决方案5】:

      用这个来拒绝。核心。请仔细阅读此链接,并查看作者试图在虚拟设备和真实设备之间进行区分。

      代码来自THIS SITE

      /**
       * 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());
              Log.d(TAG, "CPU Count: "+files.length);
              //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;
          }
      }
      

      【讨论】:

        【解决方案6】:

        给你(Java):

            try {
                int ch, processorCount = 0;
                Process process = Runtime.getRuntime().exec("cat /proc/cpuinfo");
                StringBuilder sb = new StringBuilder();
                while ((ch = process.getInputStream().read()) != -1)
                    sb.append((char) ch);
                Pattern p = Pattern.compile("processor");
                Matcher m = p.matcher(sb.toString());
                while (m.find())
                    processorCount++;
                System.out.println(processorCount);
            } catch (IOException e) {
                e.printStackTrace();
            }
        

        【讨论】:

          【解决方案7】:

          如果可能的话,最好在项目中使用 JNI

          std::thread::hardware_concurrency()

          【讨论】:

            【解决方案8】:

            kotlin 中不错且简单的解决方案:

            fun getCPUCoreNum(): Int {
              val pattern = Pattern.compile("cpu[0-9]+")
              return Math.max(
                File("/sys/devices/system/cpu/")
                  .walk()
                  .maxDepth(1)
                  .count { pattern.matcher(it.name).matches() },
                Runtime.getRuntime().availableProcessors()
              )
            }
            

            【讨论】:

              猜你喜欢
              • 2015-12-08
              • 2014-05-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-07-17
              • 1970-01-01
              相关资源
              最近更新 更多