Measure time in function in C

I am debugging a C application and I would like to know how much time it spends in a specific function.

I could change the source code and add some more code to measure, but this does not seem right to me. I would prefer to do this with an external application without recompiling every time.

I found out that you can set a breakpoint in GDB, so I thought: it should be possible to track the time using a similar tool with a simple procedure: - set a breakpoint - when stopped, measure the actual time and run the function - when you exit the function, measure the time again However, I did not find a way to do this in gdb :(

any ideas? Thanks

+5
source share
5 answers

If you use GCC, you need the compilation option "-pg" and the application gprof.

+2
source

gprofis only reliable - in my experience, it works only on everyone - if you statically link -pgcompiled versions of each library, including the C library. You can try to do this with the gcc option -profile(which does what it -pgdoes plus, tries to connect to the sub in the libraries -pg), but the problem is that GNU libc really does not like to be statically linked, and your distribution cannot provide -pgcompiled versions of every library that you need.

cachegrind, valgrind . . ; , . 2 .

perf - . , , , . . ( http://web.eecs.utk.edu/~vweaver1/projects/perf-events/, API, , - .)

+2

~/.gdbinit:

define timeme
set $last=clock()
n
set $timing=clock() - $last
if $timing>$arg0
printf "***long***\n"
end
printf "%d cycles, %f seconds\n", $timing, (float)$timing / 1000000
end

1000000 , CLOCKS_PER_SEC .

; , :

Breakpoint 2, install_new_payload_from_meta (snmp_meta=0x7eee81c0, pkt=0x0, entry=0x7d4f4e58) at /home/sgillibr/savvi-dc-snmp/recipies.c:187
(gdb) timeme 100000
***long***
580000 cycles, 0.580000 seconds
(gdb)

, , .

+2

- , , , . prof gprof.

UPDATE: "cc -Wall -ggdb -pg -g3 -O2 diskhash.c -o diskhash" ( ), "gprof -p diskhash" :

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total           
 time   seconds   seconds    calls  ms/call  ms/call  name    
 32.60      0.41     0.41        1   410.75   646.18  create_hashtab
 31.80      0.81     0.40  5087692     0.00     0.00  hash_func
 27.83      1.16     0.35  2543846     0.00     0.00  find_hash
  2.78      1.20     0.04  2543846     0.00     0.00  chop_a_line
  1.59      1.22     0.02                             main
  0.40      1.22     0.01                             frame_dummy
  0.00      1.22     0.00        4     0.00     0.00  map_da_file
+1

~/.gdbinit

define timeme
    python import time
    python starttime=time.time()
    next
    python print("Previous takes: " + (str)(time.time()-starttime) + "s")
end
document timeme
    Measure executing time of next function
    Usage: timeme or ti
end

timeme ti, .

+1

All Articles