Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthreads: programmatically gather information on time spent on different states?

Tags:

c

linux

pthreads

In C, Linux 3.2: Is there a way to programmatically gather stats on the state of each pthread created thread on some program? For instance, I'd like to get the time each thread spent running, and in the idle state.

like image 725
Dervin Thunk Avatar asked May 27 '12 14:05

Dervin Thunk


People also ask

What are pthreads used for?

POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.

What is pthreads scheduling?

Scheduling. You use the Pthreads scheduling features to set up a policy that determines which thread the system first selects to run when CPU cycles become available, and how long each thread can run once it is given the CPU.

How is pthreads implemented?

Pthreads are implemented as user threads by the runtime library. Most portable implementation since it requires no kernel support. Fast context switches between user threads because it is handled entirely in user space without the overhead of the kernel implementing a process-level context switch.

What is pthread_join used for?

The pthread_join() function provides a simple mechanism allowing an application to wait for a thread to terminate. After the thread terminates, the application may then choose to clean up resources that were used by the thread.


2 Answers

clock_gettime() can return the thread-specific CPU time. Simply do:

struct timespec ts;
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);

But from my understanding this is the sum of user and system time of this thread. Also you should consider the Warning message regarding SMP systems at the end of the man page.

Also, if you don't want timing information on the current thread, but on some pthread, you could get the clockid_t to use with clock_gettime() using int pthread_getcpuclockid(pthread_t thread, clockid_t *clock_id).

like image 121
Florian Sowade Avatar answered Oct 13 '22 00:10

Florian Sowade


getrusage()

EDIT: To get idle time, I would subtract the system and user time from the total time the thread was active.

Other tools you can use to probe include: system tap, swtrace, tprof, oprofile, perf, sysprof, ptt, etc.

like image 40
johnnycrash Avatar answered Oct 12 '22 22:10

johnnycrash