2011-09-14 43 views
5

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

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

我发现有可能建立一个破发点中的GDB,所以我想,它必须能够通过简单的程序,使用类似的工具来跟踪时间: - 设置断点 - 停止时,测量实际时间和运行功能 - 离开功能时,重新测量时间 但是,我还没有找到一种方法如何在gdb :(

任何想法做到这一点感谢

回答

2

如果你使用GCC,你想要什么?编译选项“-pg”和应用程序gprof

+0

'gprof'会告诉我一个函数被调用了多少次,但不想让我看看时间。它只是说“没有时间积累” –

+0

然后也许它被优化了或什么的。 –

1

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

UPDATE:以 “CC -Wall -ggdb -pg -g3 -02 diskhash.c -o diskhash” compilng(运行程序), “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 
2

gprof只有可靠 - 根据我的经验,仅适用于所有 - 如果您静态链接每个库(包括C库)的编译版本-pg。您可以尝试使用gcc的-profile选项(这是做什么-pg不会做什么加试图在-pg库)但问题是,GNU libc真的不喜欢被静态链接,并且您的发行版可能不会提供-pg编译版本你需要的每一个图书馆。

我建议你试试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) 

显然分辨率可能是不够的一些需求,虽然它被证明是非常有用的。

+0

我试过它在C文件中的sleep()函数,它不工作,结果始终为0。 – CodyChan

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 

timemeti