How to find total time used by the thread in C/C++?

663 views Asked by At

I am trying to get the total time a particular thread spent so far programatically.

getrusage returns a thread's CPU time but I want the total time i.e. including the time spent by the thread being blocked for whatever reason.

Please note that I will be making use of this functionality by instrumenting a given program using a profiler that I wrote.

A program may have many threads (I am focusing on profiling servers so there can be many). At any given time I would want to know how much time a particular thread spent (so far). So its not convenient to start a timer for every thread as they are spawned. So I would want something of usage similar to getrusage e.g. it returns the total time of the current thread or maybe I can pass to it a thread id. So manual mechanisms like taking a timestamp when the thread was spawned and one later then taking their difference won't be very helpful for me.

Can anyone suggest how to do this?

Thanks!

2

There are 2 answers

4
R.. GitHub STOP HELPING ICE On

Save the current time at the point when the thread is started. The total time spent by the thread, counting both running and blocked time, is then just:

current_time - start_time

Of course this is almost always useless/meaningless, which is why there's no dedicated API for it.

0
Chris Cochran On

Depending on what you want to use this for, one possibility to think about is to sum the number of clock ticks consumed during blocking, which typically is slow enough hide a little overhead like that. So from that sum and the surrounding thread interval you also measure, you can compute the real time load on your thread over that interval. Of course, time-slicing with other processes will throw this off some amount, and capturing all blocking may be very easy or very hard, depending on your situation.