简体   繁体   中英

How to measure execution time of thread in macos?

Is there any way to measure execution time of thread under 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). I need to measure time of thread (the sum of processed time in user and kernel spaces). The exact analogue is GetThreadTimes under Windows ( https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadtimes )

You can pass RUSAGE_THREAD for the first parameter to getrusage .

Edit: Looks like Mac supports only RUSAGE_SELF and RUSAGE_CHILDREN .

CLOCK_THREAD_CPUTIME_ID is another option, which tracks CPU time for a calling thread. Note that this is CPU time and not wall clock time, ie for example any time spent sleeping won't be accounted for.

#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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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