41

I was looking to determine(or count) the number of cores in the embedded processor of android device.

I tried using /proc/cpuinfo, but it is not returning the number of cores of device !

I don't found the code anywhere on the Internet. Does anyone here know how can I determine this, then please answer. Thanks in advance

UPDATE:

The answers on this question How can you detect a dual-core cpu on an Android device from code? doesn't run well in some devices. I tested them is dual core & quad core processors, they returned 2 & 4 respectively, fine !

But, On Octa Core processor like in Samsung Note 3 it returned 4. (Perhaps in note 3 there are 2 sets of quad core processors running individually )

I was looking to solve this problem.

UPDATE

The app CPU-Z is returning the correct core count in my device Samsung note 3 enter image description here Here it seems that there exists a possible solution...

Community
  • 1
  • 1
Vivek Warde
  • 1,936
  • 8
  • 47
  • 77

8 Answers8

54

You may use a combination of above answer with this one. This way it will perform faster on devices running API 17+ as this method is much faster than filtering out files.

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 ()

Added in API level 1 Returns the number of processor cores available to the VM, at least 1. Traditionally this returned the number currently online, but many mobile devices are able to take unused cores offline to save power, so releases newer than Android 4.2 (Jelly Bean) return the maximum number of cores that could be made available if there were no power or heat constraints.

Also there is information about number of cores inside a file located in /sys/devices/system/cpu/present It reports the number of available CPUs in the following format:

  • 0 -> single CPU/core
  • 0-1 -> two CPUs/cores
  • 0-3 -> four CPUs/cores
  • 0-7 -> eight CPUs/cores

etc.

Also please check what is inside /sys/devices/system/cpu/possible on a note 3

Both files have r--r--r-- or 444 file permissions set on them, so you should be able to read them without a rooted device in code.

EDIT: Posting code to help you out

 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) {
                }
            }
        }
    }

With the result

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

The test was run on OnePlus One running BlissPop ROM with Android v5.1.1 and it prints as it should. Please try on your Samsung

Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
10

Firstly, it seems like this is not possible, here is some information on this:

We will use the Samsung Exynos 5 Octa CPU as an example for this thread, but generally any ARM processor will work the same.

The Samsung Exynos 5 Octa CPU has 8 CPU cores. but in reality it has two processes with 4 cores each. This is called big.LITTLE. You have 1 fast processor and 1 power efficient processor.

Within the Exynos 5 CPU it has two different CPUs in built, a Cortex a15 and a Cortex a7...

Within big.LITTLE both CPUs cannot run at the same time, only one CPU can be active at any given time...

But there is also something called "big.LITTLE mp" in which both CPU's can be active at the same time, but here is the catch (again!) Only FOUR cores can be active to the software at any given time. Here is an image to explain this a bit better:

big.LITTLE mp

Now as you can see, a single CPU core is used from the more powerful processor here and then the other four cores are active from the more energy efficient a7 CPU cluster.

You can read more about the big.LITTLE architecture here : http://www.arm.com/products/processors/technologies/biglittleprocessing.php

You can read more about the big.LITTLE mp architecture here: http://www.arm.com/products/processors/technologies/biglittleprocessing.php

What you want to find out now, is if it is possible to know if the CPU architecture is Big.LITTLE or BIG.LITTLE mp. Then see if you can directly find out the CPU count from each individual CPU, but I cannot find any relevant code. There is a lot of documentation on ARMs website, but I am not too sure if it is possible to get this information. Either way though, only 4 CPU cores can be used therefor the code you have is technically correct as that is the number of useable cores.

I hope this helped, if you have any questions or want anything clearing up then let me know. There is a lot of information out there

apmartin1991
  • 3,064
  • 1
  • 23
  • 44
  • Thanks for making it more clear the problem. But the app CPU-Z is doing what I want. Look at my screenshot, I edited the question – Vivek Warde May 15 '15 at 14:46
  • 4
    It is possible that CPU-Z is looking at the model information and pulling the rest of the data from an online source. I will take a look further tonight. Sadly I do not have a phone in which I can test with so it will be difficult. – apmartin1991 May 15 '15 at 15:15
  • Ya, it could also be possible that it some function my return the keyword `octa, , `quad`, or `dual` like so – Vivek Warde May 15 '15 at 18:06
  • 1
    Correct, that is always an option. It is always work emailing CPU-Z support, they may be able to help! – apmartin1991 May 15 '15 at 18:13
  • @VivekWarde if you are really so interested in how cpu-z, why don't you try to decompile it and see what is going on? – Bojan Kseneman May 16 '15 at 09:09
  • @BojanKseneman I already decompiled it by decompileandroid.com but I didn't find this solution – Vivek Warde May 16 '15 at 13:22
  • @VivekWarde I think it uses some kind of database. Local or remote, check for that. It may be doing a lookup for a cpu from it – Bojan Kseneman May 16 '15 at 15:05
  • Okay, do the following: On your device put airplane mode on, then clear data from CPU-Z and cache, force stop the application... Then open the application, if it displays 8 cores then they do it in code, if it says 4 or nothing then it does it via looking at a database online or on the device... – apmartin1991 May 16 '15 at 17:35
  • @VivekWarde did you find a solution? – Binoy Babu Jun 30 '15 at 19:19
  • @BinoyBabu no, are you making a similar project?' – Vivek Warde Jul 04 '15 at 12:27
  • @VivekWarde I have made a similar app. In fact I did analyse the cpuZ app and found that they are using a proprietary native library libcpuid.so to gather this information. – Binoy Babu Jul 31 '15 at 04:25
  • @BinoyBabu Please Contact me I am still facing this problem. Please add me on skype. My skype id is: vivek.warde9 – Vivek Warde Aug 12 '15 at 16:14
  • @VivekVarde can't find you. Contact me at royale1223 [at] gmail.com – Binoy Babu Nov 13 '15 at 09:15
  • @apmartin1991 I believe this answer is now out of date, as with "Global Task Scheduling" it *is* now possible for all the cores in a big.LITTLE SoC to be used at once (see number 1.) in: https://community.arm.com/groups/processors/blog/2013/06/18/ten-things-to-know-about-biglittle – Maks Feb 11 '16 at 01:42
7

Try this:

Runtime.getRuntime().availableProcessors();

This returns the number of CPU's available for THIS specific virtual machine, as I experienced. That may not be what you want, still, for a few purposes this is very handy. You can test this really easily: Kill all apps, run the above code. Open 10 very intensive apps, and then run the test again. Sure, this will only work on a multi cpu device, I guess.

SilentKnight
  • 13,761
  • 19
  • 49
  • 78
4

You can try this method to get number of core.

 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;
      }
Saurabh Ande
  • 427
  • 3
  • 13
1

Use this to get no. of cores.Do read this link very carefully and also see what the author is trying to tell between virtual device and a real device.

The code is referred from 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;
    }
}
Misch
  • 10,350
  • 4
  • 35
  • 49
Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
1

Nice and simple solution in 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()
  )
}
G00fY
  • 4,545
  • 1
  • 22
  • 26
1

Here you go (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();
    }
Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
0

good thing is to use JNI, if possible in project

std::thread::hardware_concurrency()