views:

151

answers:

2

I want to know whether I can calculate the running time for each thread. I implement a multithread program in C++ using pthread. As we know, each thread will compete the CPU. Can I use clock() function to calculate the actual number of CPU clocks each thread consumes?

my program looks like:

Class Thread ()
{
Start();
Run();
Computing();
};

Start() is to start multiple threads. Then each thread will run Computing function to do something. My question is how I can calculate the running time of each thread for Computing function

+2  A: 

No, you cannot use clock. Processor could switch to another thread between Start and Computing calls so you will calculate the time of several threads. You need to use tick counter local for one thread.

Kirill V. Lyadvinsky
Do you mean clock will include the running time for all threads? If so what I want is to use tick counter local for each thread. Could you pls give more explanations for tick counter?
chnet
Yes about `clock`. But thread local counters is a platform specific feature, what platform do you use?
Kirill V. Lyadvinsky
i686-apple-darwin9-g++-4.0.1
chnet
Any other information needed?
chnet
Sorry, can't consult about apple.
Kirill V. Lyadvinsky
+1  A: 

What platform are you using? If you are using Linux and are on kernel > 2.6.26 you can use the RUSAGE_THREAD flag to getrusage:

struct rusage usage
getrusage(RUSAGE_THREAD, &usage);

within struct rusage, you'll find ru_utime and ru_stime which tracks user time and system time respectively. Call this once at the beginning and once after and you can get the delta.

R Samuel Klatchko