在macos下有没有办法测量线程的执行时间?我知道有 getrusage
函数,但它应该只测量进程时间(在 linux 下有测量线程时间的扩展,但不幸的是我在 MacOs 下工作)。我需要测量线程的时间(用户空间和内核空间中处理时间的总和)。确切的类似物是 GetThreadTimes
(https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadtimes)
Windows
答案 0 :(得分:1)
您可以将第一个参数的 RUSAGE_THREAD
传递给 getrusage
。
编辑:
看起来 Mac 只支持 RUSAGE_SELF
和 RUSAGE_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);
}