-   Programming (
-   -   CPU time of C++ programme (

unihiekka 06-20-2008 12:28 PM

CPU time of C++ programme
Is there a (standard) way of getting the CPU time used by a (part of a) C++ programme, such that I can print it on screen or append to a data file created by the programme itself? The clock function works nicely if I want the elapsed time, but I need the actual CPU time, if that's possible.


jim mcnamara 06-20-2008 01:21 PM

getrusage() gives cpu time in kernel & user mode, but for the program as a whole and separately for the children as a whole.

For a particular function, there is no good run-time way to do this. However check at There are profiling tools there. But profiling adds a lot of overhead to your program.

This leaves two options -
use gprof the gnu profiler
"manually" keep track of cpu usage into and out of a particular function with getrusage and delta times.

Try gprof first. Compile with with gcc -g -p -o filename filename.c.
Running the code produces an output file, usually mon.out. gprof filename produces a lot of output. See if that doesn't do what you want before going to a lot of trouble. Re-compile without -p -g after you work out problems with performance.

All times are GMT -5. The time now is 03:39 AM.