如何测量macos中线程的执行时间?

How to measure execution time of thread in macos?

有什么方法可以测量macos下线程的执行时间吗?我知道有 getrusage 函数,但它应该只测量处理时间(在 linux 下有测量线程时间的扩展,但不幸的是我在 MacOs 下工作)。我需要测量线程时间(用户和内核空间中处理时间的总和)。确切的类似物是 Windows 下的 GetThreadTimes (https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadtimes)

您可以将第一个参数 RUSAGE_THREAD 传递给 getrusage

编辑: 看起来 Mac 只支持 RUSAGE_SELFRUSAGE_CHILDREN.

CLOCK_THREAD_CPUTIME_ID 是另一个选项,它跟踪调用线程的 CPU 时间。请注意,这是 CPU 时间而不是挂钟时间,例如,任何睡眠时间都不会被计算在内。

#include <stdio.h>
#include <pthread.h>
#include <time.h>

void* thread_func(void* args)
{
        struct timespec tp;
        ret = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp);
        printf("thread elapsed secs: %ld nsecs %ld\n", tp.tv_sec, tp.tv_nsec);
}
int main()
{
        pthread_t thread;
        pthread_create(&thread, NULL, thread_func, NULL);
        pthread_join(thread, NULL);
}