[英]Get current pthread cpu usage Mac OS X
在 Mac OS X 中如何從線程本身獲取線程的 CPU 時間? 對於 linux,我所做的是getrusage(RUSAGE_THREAD, &ru)
但此解決方案不適用於 Mac OS X。
我遇到了這個問題,但我不知道如何根據我的目的調整它(我不熟悉 Mac OS X 的內部結構。我什至不確定 pthread thread == mach thread)。
這就是我最終的結果:
#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)
得到的結果getrusage(RUSAGE_THREAD, &ru)
。 所以我不確定這是正確的方法。
如果你正在使用 pthread api 無論如何,他也應該做這個工作:
#include <unistd.h>
#include <pthread.h>
#include <libproc.h>
#include <stdio.h>
[...]
uint64_t tid;
pthread_threadid_np(NULL, &tid);
struct proc_threadinfo pth;
if (PROC_PIDTHREADINFO_SIZE ==
proc_pidinfo(getpid(), PROC_PIDTHREADID64INFO, tid, &pth,
PROC_PIDTHREADINFO_SIZE)) {
printf("user time in ns: %llu\nsystem time in ns: %llu\n",
pth.pth_user_time, pth.pth_system_time);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.