866 Subj : Re: Per thread cpu-usage on Linux To : comp.programming.threads From : Christoph Bartosch Date : Wed Feb 16 2005 04:49 pm 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 . 0