John Roberts
John Roberts

Reputation: 5966

Programmatically Getting Total Time and Busy Time of Function on Linux

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

Answers (3)

Santhosh Pai
Santhosh Pai

Reputation: 2625

You can use gprof for the same.

Upvotes: 1

Mike Dunlavey
Mike Dunlavey

Reputation: 40649

  1. 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.

  2. 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).

  3. 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

unwind
unwind

Reputation: 399703

Yes, you can use gprof, but that requires re-compiling the binary you want to measure to insert the required monitoring code. By default, programs don't spend time recording this data, so you must add it. With gcc, this is done using the -pg option.

Upvotes: 1

Related Questions