To be honest, it's so hard to dig into the kernel that I only found the way to get it in C++. Hopes that may help.
Runtime.availableProcessors();
public int availableProcessors() {
return (int) Libcore.os.sysconf(_SC_NPROCESSORS_CONF);
}
You can reference the source code from sysinfo.cpp.
int __get_cpu_count(const char* sys_file) {
int cpu_count = 1;
FILE* fp = fopen(sys_file, "re");
if (fp != nullptr) {
char* line = nullptr;
size_t allocated_size = 0;
if (getline(&line, &allocated_size, fp) != -1) {
cpu_count = GetCpuCountFromString(line);
}
free(line);
fclose(fp);
}
return cpu_count;
}
int get_nprocs_conf() {
// It's unclear to me whether this is intended to be "possible" or "present",
// but on mobile they're unlikely to differ.
return __get_cpu_count("/sys/devices/system/cpu/possible");
}
int get_nprocs() {
return __get_cpu_count("/sys/devices/system/cpu/online");
}
Also sees cpustats.c.
/*
* Get the number of CPUs of the system.
*
* Uses the two files /sys/devices/system/cpu/present and
* /sys/devices/system/cpu/online to determine the number of CPUs. Expects the
* format of both files to be either 0 or 0-N where N+1 is the number of CPUs.
*
* Exits if the present CPUs is not equal to the online CPUs
*/
static int get_cpu_count() {
int cpu_count = get_cpu_count_from_file("/sys/devices/system/cpu/present");
if (cpu_count != get_cpu_count_from_file("/sys/devices/system/cpu/online")) {
die("present cpus != online cpus\n");
}
return cpu_count;
}
/*
* Get the number of CPUs from a given filename.
*/
static int get_cpu_count_from_file(char* filename) {
FILE* file;
char line[MAX_BUF_SIZE];
int cpu_count;
file = fopen(filename, "r");
if (!file) die("Could not open %s\n", filename);
if (!fgets(line, MAX_BUF_SIZE, file)) die("Could not get %s contents\n", filename);
fclose(file);
if (strcmp(line, "0\n") == 0) {
return 1;
}
if (1 == sscanf(line, "0-%d\n", &cpu_count)) {
return cpu_count + 1;
}
die("Unexpected input in file %s (%s).\n", filename, line);
return -1;
}