简体   繁体   English

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

[英]How to measure execution time of thread in macos?

Is there any way to measure execution time of thread under macos?有什么方法可以测量macos下线程的执行时间吗? I know that there is getrusage function, but it is supposed only to measure process time (Under linux there is extension to measure thread time, but unfortunately I work under MacOs).我知道有getrusage function,但它应该只测量进程时间(在linux下有测量线程时间的扩展,但不幸的是我在MacOs下工作)。 I need to measure time of thread (the sum of processed time in user and kernel spaces).我需要测量线程的时间(用户处理时间和 kernel 空间的总和)。 The exact analogue is GetThreadTimes under Windows ( https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadtimes )确切的类比是Windows下的GetThreadTimes ( https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadtimes )

You can pass RUSAGE_THREAD for the first parameter to getrusage .您可以将第一个参数的RUSAGE_THREAD传递给getrusage

Edit: Looks like Mac supports only RUSAGE_SELF and RUSAGE_CHILDREN .编辑:看起来 Mac 只支持RUSAGE_SELFRUSAGE_CHILDREN

CLOCK_THREAD_CPUTIME_ID is another option, which tracks CPU time for a calling thread. CLOCK_THREAD_CPUTIME_ID是另一个选项,它跟踪调用线程的 CPU 时间。 Note that this is CPU time and not wall clock time, ie for example any time spent sleeping won't be accounted for.请注意,这是 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM