Subj : Re: Per thread cpu-usage on Linux To : comp.programming.threads From : John G. Shaw Date : Wed Feb 16 2005 09:36 am Christian Panten wrote: > Hi, > > I have a problem to calculate the cpu time used by a thread... > The problem exists on several linux- and unix-systems. > > First I try to describe what I want to calculate: > I work on a program which I have parallelized with pthreads. Now I want > to calculate some times. > 1. The running time of the whole programm: no problem: I use the > real-timer. > 2. The cpu running time of all threads: there is still a problem because > there are varieties on several systems. But this is not the problem I > want to discuss here. > > 3. My problem mow: I want to calculate the cpu-time of one thread (the > thread is still running). > This I know: > Linux-kernel 2.4: I can calculate the cpu-time of a thread by using > times(), because each thread seems to have its own counter. > > Linux-kernel 2.6 with NPTL: The function times() returns the total > cpu-time of the whole process. And I don't know how to get separate > times for each thread. > > I have made some trials: > - calculate the cpu-time with clock_gettime(CLOCK_THREAD_CPUTIME_ID, ..) > - reading the cpu-time from /proc/self/task/*ID*/stat > - calculate the cpu-time with clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ..) > > I wrote a test-program with 10 threads for a linux-server with 8 > processors. In doing so the times calculated with > CLOCK_THREAD_CPUTIME_ID and CLOCK_PROCESS_CPUTIME_ID are nearly equal > and the time read from /proc/... is in parts lower about several seconds > as both cpu-timer, but not all the time. > > Here one line from my test-program: (kernel 2.6) > thread: 6.470 read from /proc/... > cpu: 10.220 calculated with CLOCK_PROCESS_... > times: 72.420 calculated with times() > thread2: 10.219 calculated with CLOCK_THREAD_... > > I hope you can help me... > 1. Does anyone know how I can calculate the cpu-time of single thread? > Reading the cpu time from /proc/... is not a satisfactory solution for me. > 2. Does anyone know how I can solve the same problem with AIX 5.1? > > Thx for your help... > > Best regards > Christian Try something like the following using pthread_getcpuclockid() static double timespec_to_double(struct timespec &ts) { const double ns_to_sec= 1.0e-9; double t= double(ts.tv_sec) + double(ts.tv_nsec)*ns_to_sec; return t; } // beginning of section to time clockid_t clock_id; pthread_getcpuclockid(pthread_self(),&clock_id); struct timespec ts; clock_gettime(clock_id,&ts); double cpuTime0= timespec_to_double(ts); // do it again at end of section to time (in the thread) // then subtract the two cputimes as usual. -- ***************************************************** John G. Shaw To reply, remove "noSpam" from the reply-to field. ***************************************************** .