I'm trying to write code for Android which would give me some kind of information (id?) of the processor and the core on which a thread is running on.
I've google'd and grep'ed the sources for some inspiration but with no luck. All I know is, that most likely I will need some C/C++ calls.
What I have working is the following:
#include <jni.h>
int getCpuId() {
// missing code
return 0;
}
int getCoreId() {
// missing code
return 0;
}
JNIEXPORT int JNICALL Java_com_spendoptima_Utils_getCpuId(JNIEnv * env,
jobject obj) {
return getCpuId();
}
JNIEXPORT int JNICALL Java_com_spendoptima_Utils_getCoreId(JNIEnv * env,
jobject obj) {
return getCoreId();
}
The whole project compiles and runs just fine. I'm able to call the functions from within Java and I get the proper responses.
Is here anybody who could fill in the blanks?
This is what seems to work for me:
//...
#include <sys/syscall.h>
//...
int getCpuId() {
unsigned cpu;
if (syscall(__NR_getcpu, &cpu, NULL, NULL) < 0) {
return -1;
} else {
return (int) cpu;
}
}
//...
The good news is, the necessary library and system call are defined on Android (sched_getcpu() and __getcpu()). The bad news is, they aren't part of the NDK.
You can roll your own syscall wrapper and library call, using the method shown in this answer.
Another approach is to read /proc/self/stat
and parse out the processor
entry. The proc(5) man page describes the format:
/proc/[pid]/stat Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c. ... processor %d (since Linux 2.2.8) CPU number last executed on.
This is much slower, and the "file" format may change if the kernel is updated, so it's not the recommended approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With