【问题标题】:Android: Find out which core the thread is running onAndroid:找出线程在哪个内核上运行
【发布时间】:2014-02-02 13:32:35
【问题描述】:

我正在尝试为 Android 编写代码,它会给我一些关于处理器和线程运行的内核的信息(id?)。

我已经用谷歌搜索并搜索了一些灵感来源,但没有运气。我所知道的是,我很可能需要一些 C/C++ 调用。

我的工作如下:

#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();
}

整个项目编译并运行良好。我能够从 Java 中调用函数并得到正确的响应。

这里有人可以填空吗?

【问题讨论】:

  • 您在寻找getcpu() / sched_getcpu()吗? stackoverflow.com/questions/491520/…
  • 据我所知,sched_getcpu 仅针对 mips 架构实现。我尝试将其移植到 arm,但出现编译错误。 __getcpu 找不到,或类似的东西。

标签: android multithreading concurrency android-ndk java-native-interface


【解决方案1】:

这似乎对我有用:

//...
#include <sys/syscall.h>
//...
int getCpuId() {

    unsigned cpu;
    if (syscall(__NR_getcpu, &cpu, NULL, NULL) < 0) {
        return -1;
    } else {
        return (int) cpu;
    }
}
//...

【讨论】:

    【解决方案2】:

    好消息是,必要的库和系统调用是在 Android 上定义的(sched_getcpu()__getcpu())。坏消息是,它们不是 NDK 的一部分。

    您可以使用this answer 中显示的方法滚动您自己的系统调用包装器和库调用。

    另一种方法是读取/proc/self/stat 并解析出processor 条目。 proc(5) man page 描述格式:

      /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.
    

    这样会慢很多,而且如果内核更新,“文件”格式可能会改变,所以不推荐这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-27
      • 2016-08-28
      • 2011-12-23
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多