Subj : Re: Per thread cpu-usage on Linux To : comp.programming.threads From : Christoph Bartoschek Date : Thu Feb 17 2005 10:58 am David Schwartz wrote: > > "John G. Shaw" wrote in message > news:1117lllc05lhi4d@corp.supernews.com... > >> 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. (???) > > Does clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...); work? > > DS I've put the measurment in a separate thread and tried CLOCK_THREAD_CPUTIME_ID. Both lead to the same results. 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; } extern "C" void * execute(void *) { clockid_t clock_id; pthread_getcpuclockid(pthread_self(),&clock_id); struct timespec ts; //clock_gettime(clock_id,&ts); clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts); double cpuTime0= timespec_to_double(ts); for (int i = 0;i != 5; ++i) { sleep(1); //clock_gettime(clock_id,&ts); clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts); double cpuTime1= timespec_to_double(ts); std::cout << "Time: " << cpuTime1-cpuTime0 << std::endl; } return 0; } int main() { pthread_t tid; pthread_create(&tid, 0, execute, 0); pthread_join(tid, 0); } [ponto@burns ponto]$ g++ thread.C -pedantic -Wall -W -g -pthread -lrt [ponto@burns ponto]$ ./a.out Time: 1.00561 Time: 2.05453 Time: 3.15841 Time: 4.16581 Time: 5.17434 .