测量C中函数的时间

我正在调试一个C应用程序,我想知道它在特定函数中花费了多少时间。

我可以更改源代码并添加更多代码来进行测量,但对我来说似乎并不合适。 我宁愿用外部应用程序来做,而不是每次都重新编译。

我发现可以在GDB中设置一个断点,所以我想,必须能够通过简单的程序使用类似工具跟踪时间: – 设置断点 – 停止时,测量实际时间并运行函数 – 离开函数时,再次测量时间然而,我还没有找到一种方法如何在gdb中做到这一点:(

有任何想法吗? 谢谢

如果您正在使用GCC,则需要编译选项“-pg”和应用程序gprof

gprof只是可靠的 – 根据我的经验,只适用于 – 如果你静态链接每个库的编译版本,包括C库。 您可以尝试使用gcc的-profile选项(它执行-pg确实加上尝试sub-in -pg库)但问题是,GNU libc真的不喜欢静态链接,并且您的发行版可能不提供-pg您需要的每个库的编译版本。

我建议你尝试cachegrind ,这是一种valgrind操作模式,只需要调试信息。 这更容易获得。 问题是,它有巨大的管理费用; 太大了,它可能会使你的测试无效。 预计至少减速2倍。

你也可以尝试一下 – 如果你能得到一份副本。 它非常聪明,但对于那些认为人们喜欢从头开始构建东西的内核黑客来说,它是由内核黑客提供的。 我的运气很好。 (请阅读http://web.eecs.utk.edu/~vweaver1/projects/perf-events/ ,这是关于底层API,而不是实用程序,但可能仍然可以节省大量浪费的时间。)

我的〜/ .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) 

显然,对于某些需求而言,解决方案可能还不够,尽管它确实非常有用。

分析可能就是你想要的。 看看prof或gprof。

更新:用“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 

把它放到你的〜/ .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 

如果要测量下一个function的时间,请输入timemeti