Reputation: 5966
Is there any way to programmatically get the total time that a C program has been running, as well as the amount of that time spent inside a particular function? I need to do this in the code since I want to use these two values as arguments for another function. Since I am on Linux, would I be able to use gprof or perf to do this?
Upvotes: 2
Views: 277
Reputation: 40649
Grab the system time when the program starts. Then, whenever you want, you can get the current time and subtract the start time. That tells how long you've been running, in wall-clock time.
Have a global boolean Q that is set True when your function is entered, and False when it exits, so it is only True while the program is "in" the function (inclusively).
Setup a timer interrupt to go off every N ms, and have two global counters, A and B. (N does not have to be small.) When the timer interrupts, have it increment B regardless, but only increment A if Q is true.
This way, you know how much time has elapsed, and A/B is the fraction of that time your function was on the stack.
BTW: If the function is recursive, let Q be an integer "depth counter". Otherwise, no change.
Upvotes: 2