获取当前的pthread cpu使用率Mac OS X.

时间:2012-12-15 14:39:19

标签: c macos pthreads cpu-usage

如何在Mac OS X中从线程本身获取线程的cpu时间?对于linux,我所做的是getrusage(RUSAGE_THREAD, &ru),但此解决方案不适用于Mac OS X.

我遇到了这个question,但我不知道如何根据我的目的调整它(我不熟悉Mac OS X的内部。我甚至不确定pthread thread == mach thread)。

1 个答案:

答案 0 :(得分:5)

这就是我最终的结果:

#include <mach/mach_init.h>
#include <mach/thread_act.h>
#include <mach/mach_port.h>

[...]

mach_port_t thread;
kern_return_t kr;
mach_msg_type_number_t count;
thread_basic_info_data_t info;

thread = mach_thread_self();

count = THREAD_BASIC_INFO_COUNT;
kr = thread_info(thread, THREAD_BASIC_INFO, (thread_info_t) &info, &count);

if (kr == KERN_SUCCESS && (info.flags & TH_FLAGS_IDLE) == 0) {
    usage->utime.tv_sec  = info.user_time.seconds;
    usage->utime.tv_usec = info.user_time.microseconds;
    usage->stime.tv_sec  = info.system_time.seconds;
    usage->stime.tv_usec = info.system_time.microseconds;
}
else {
    // should not happen
    printf("Could not retreive thread info.");
    bzero(usage, sizeof(struct usage));
}

mach_port_deallocate(mach_task_self(), thread);

我得到的结果与我在Linux下使用getrusage(RUSAGE_THREAD, &ru)获得的结果非常不同。所以我不确定这是正确的方法。