Subj : Re: Per thread cpu-usage on Linux To : comp.programming.threads From : John G. Shaw Date : Wed Feb 16 2005 06:26 pm Christoph Bartosch wrote: > John G. Shaw wrote: > > >>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. >> > > > Hi, this seems not to work because the function seems to measure realtime. > The following programm using only the main thread should illustrate it: > > extern "C" { > #include > #include > #include > #include > #include > #include > #include > } > > #include > > 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; > } > > int main() > { > clockid_t clock_id; > pthread_getcpuclockid(pthread_self(),&clock_id); > struct timespec ts; > clock_gettime(clock_id,&ts); > double cpuTime0= timespec_to_double(ts); > > for (int i = 0;i != 5; ++i) > { > sleep(1); > clock_gettime(clock_id,&ts); > double cpuTime1= timespec_to_double(ts); > std::cout << "Time: " << cpuTime1-cpuTime0 << std::endl; > } > } > > bartosch@preston:~/uhren> g++ *.C -pthread -lrt > bartosch@preston:~/uhren> time ./a.out > Time: 1.00131 > Time: 2.00327 > Time: 3.00523 > Time: 4.00719 > Time: 5.00915 > > real 0m5.016s > user 0m0.001s > sys 0m0.003s > > > The measured time is 5 seconds while the used cpu time is below 0.01 > seconds. The original poster wants to measure the cpu time used by a single > thread. > > > Greets > Christoph Bartoschek The intent was to use the pthread_getcpuclockid() function within a running thread (i.e., a function invoked via pthread_create()). I'm a bit surprised it even runs under the main program (I thought pthread_self() would not be valid or even crash). I have used this approach successfully on a parallel computer (SGI Altix series), and it seems to return the thread's CPU time as opposed to "real time" in the thread. It's possible that pthread_self() does not return a thread-dependent clock_id if it is not invoked under a running pthread. It's also possible this may be a system-dependent behaviour. SGI's linux has been significantly modified from most others. (???) -- ***************************************************** John G. Shaw To reply, remove "noSpam" from the reply-to field. ***************************************************** .