简体   繁体   中英

Android: Find out which core the thread is running on

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM