How to measure execution time of thread in macos?

Viewed 238
1 Answers

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, i.e 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);
}
Related