CLOCK_THREAD_CPUTIME_ID在MacOSX上的含义

4

我有一个从Linux移植到MacOSX的函数,它利用clock_gettime和CLOCK_THREAD_CPUTIME_ID来测量进程所花费的时间。我在互联网上找到了以下代码,它可以提供与CLOCK_REALTIME等效的功能:

#ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time
    clock_serv_t cclock;
    mach_timespec_t ts;
    host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
    clock_get_time(cclock, &ts);
    mach_port_deallocate(mach_task_self(), cclock);
#else
    timespec ts;
    clock_gettime(CLOCK_REALTIME, ts);
#endif

但是我似乎找不到一个简单的方法来获取clock_gettime(CLOCK_THREAD_CPUTIME_ID, ts)。有人知道一个好的解决方案吗?


似乎已经在这里得到了答案(https://dev59.com/OG435IYBdhLWcg3w3EIi)。希望对你有帮助。 - meaning-matters
1
在我看来并不是这样的...可能只有我无法理解代码中的某些东西,但似乎它只是针对CLOCK_REALTIME。 - Leonardo Marques
我没有详细查看,只是希望它能进一步帮助你。 - meaning-matters
1个回答

1

最近,我一直在将pcsx2项目移植到Darwin/OSX平台,我需要类似于CLOCK_THREAD_CPUTIME_ID的东西。这就是我想出来的:

#include <stdint.h>

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

typedef uint64_t u64;

// gets the CPU time used by the current thread (both system and user), in
// microseconds, returns 0 on failure
static u64 getthreadtime(thread_port_t thread) {
    mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
    thread_basic_info_data_t info;

    int kr = thread_info(thread, THREAD_BASIC_INFO, (thread_info_t) &info, &count);
    if (kr != KERN_SUCCESS) {
        return 0;
    }

    // add system and user time
    return (u64) info.user_time.seconds * (u64) 1e6 +
        (u64) info.user_time.microseconds +
        (u64) info.system_time.seconds * (u64) 1e6 +
        (u64) info.system_time.microseconds;
}

// Returns the CPU time the calling thread has used (system + user) in
// units of 100 nanoseconds. The weird units are to mirror the Windows
// counterpart in WinThreads.cpp, which uses the GetThreadTimes() API.  On
// OSX/Darwin, this is only accurate up until 1ms (and possibly less), so
// not very good.
u64 Threading::GetThreadCpuTime() {
    thread_port_t thread = mach_thread_self();
    u64 us = getthreadtime(thread);
    mach_port_deallocate(mach_task_self(), thread);
    return us * 10ULL;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接