23

I've run into a problem that appears to affect only dual-core Android devices running Android 2.3 (Gingerbread or greater). I'd like to give a dialog regarding this issue, but only to my users that fit that criterion. I know how to check OS level but haven't found anything that can definitively tell me the device is using multi-core.

Any ideas?

newbyca
  • 1,523
  • 2
  • 13
  • 25

6 Answers6

46

Unfortunately for most Android devices, the availableProcessors() method doesn't work correctly. Even /proc/stat doesn't always show the correct number of CPUs.

The only reliable method I've found to determine the number of CPUs is to enumerate the list of virtual CPUs at /sys/devices/system/cpu/ as described in this forum post. The code:

/**
 * 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 one or more digits
            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;
    }
}

This Java code should work in any Android application, even without root.

Dziugas
  • 1,500
  • 1
  • 12
  • 28
David
  • 1,698
  • 16
  • 27
  • 1
    the link you've provided is dead . also, i have some questions: it doesn't require any permission, right? also, will it even work when there are more than 9 cores? – android developer Jul 16 '13 at 07:53
  • Thanks, fixed the link. You shouldn't need any special permissions to run this code (although it could change in later Android versions). If you need to support devices with more than 10 cores, the regexp should look like this: "cpu[0-9]+" (note the extra plus sign). I'll update the post to match. – David Jul 21 '13 at 12:19
  • 1
    4 on Samsung Tab 3, but should return 2 – Suvitruf - Andrei Apanasik Dec 15 '13 at 21:19
  • Perhaps it's a hyperthreaded Dual Core processor? This would appear as 4 processors to the system. – David Jan 02 '14 at 22:59
  • The [Runtime.availableProcessors()](http://developer.android.com/reference/java/lang/Runtime.html#availableProcessors()) method is fixed in Android 4.2, so this workaround only applies to older versions. – npgall Oct 06 '14 at 15:29
  • @npgall Where do you see that it's written that it's always fixed? The docs haven't changed... – android developer Jan 13 '20 at 06:18
  • That might have been from my own testing at the time. But my comment is from 6 years ago. Things definitely might have changed since then. – npgall Jan 13 '20 at 12:27
8

If you're working with a native application, you should try this:

#include <unistd.h>
int GetNumberOfProcessor()
{
    return sysconf(_SC_NPROCESSORS_CONF);
}

It work on my i9100 (which availableProcessors() returned 1).

Thai Phi
  • 81
  • 1
4

This is pretty simple.

int numberOfProcessors = Runtime.getRuntime().availableProcessors();

Typically it would return 1 or 2. 2 would be in a dual-core CPU.

DanKodi
  • 3,550
  • 27
  • 26
  • 2
    Here is an [example](https://developer.android.com/training/multiple-threads/create-threadpool.html) of using `availableProcessprs()` to determine the size of pool thread. – bachr Jun 28 '14 at 10:14
4

You can try using Runtime.availableProcessors() as is suggested in this answer

Is there any API that tells whether an Android device is dual-core or not?

---edit---

A more detailed description is given at Oracle's site

availableProcessors

public int availableProcessors()

Returns the number of processors available to the Java virtual machine.

This value may change during a particular invocation of the virtual machine. Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately.

Returns:

the maximum number of processors available to the virtual machine; never smaller than one

Since:

  1.4
Community
  • 1
  • 1
A.J.
  • 966
  • 1
  • 9
  • 22
  • Awesome Thanks! I hadn't seen that. Just a note: on my Motorola Droid X2 availableProcessors() returns "1" ... when it should return a 2. on a Xoom availableProcessors() correctly returns 2. any other ways? – newbyca Nov 01 '11 at 04:44
1

I use a combination of both available solutions:

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's my solution, in Kotlin, based on this one:

/**
 * return the number of cores of the device.<br></br>
 * based on : http://stackoverflow.com/a/10377934/878126
 */
val coresCount: Int by lazy {
    return@lazy kotlin.runCatching {
        val dir = File("/sys/devices/system/cpu/")
        val files = dir.listFiles { pathname -> Pattern.matches("cpu[0-9]+", pathname.name) }
        max(1, files?.size ?: 1)
    }.getOrDefault(1)
}
android developer
  • 114,585
  • 152
  • 739
  • 1,270