你可以计时在gdb中采取'步骤'吗?

时间:2018-01-23 22:42:45

标签: c debugging gdb gtk

我正在使用gdb(gtk)调试C库。

有一个功能太慢了。我试图弄清楚函数的哪个部分导致了延迟。

据我所知,一个选项可能是将手动代码/重新编译插入基准代码段,但有没有办法在gdb中执行单步执行所需的时间?

2 个答案:

答案 0 :(得分:4)

对于快速分析,您可以将此代码段放在~/.gdbinit文件中:

define timeit                                                                                                                                                                             
    python import time
    python start_time = time.time()
    step
    python print("Call took {:.4f} ms".format(time.time() - start_time))
end
document timeit
    Time execution of next function
    Usage: timeit (or ti)
end

以下是正在使用的timeit函数的示例:

$ gdb --quiet --args ./can-daemon --config=../scripts/handlers.lua vcan0
Reading symbols from ./can-daemon...done.
(gdb) b main.cpp:548
Breakpoint 1 at 0x4c5bd4: file /home/evadeflow/projects/info4/can-daemon/src/main.cpp, line 548.
(gdb) run
Starting program: /home/evadeflow/projects/info4/can-daemon/_build/can-daemon --config=../scripts/handlers.lua vcan0
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Processing messages from: vcan0 

Breakpoint 1, main (argc=3, argv=0x7fffffffdbd8) at /home/evadeflow/projects/info4/can-daemon/src/main.cpp:548
548             auto L = ::InitializeLuaInterpreter(vm, lua_can_handler_map, lua_mqtt_handler_map);
(gdb) ti
(anonymous namespace)::InitializeLuaInterpreter (vm=..., lua_can_handler_map=std::unordered_map with 0 elements, lua_mqtt_handler_map=std::unordered_map with 0 elements)
    at /home/evadeflow/projects/info4/can-daemon/src/main.cpp:469
469 {
Call took 0.0643 ms
(gdb) ti
470     L = luaL_newstate();
Call took 0.0011 ms
(gdb) ti
luaL_newstate () at /home/evadeflow/projects/info4/can-daemon/_build/lua-src/src/lauxlib.c:648                                                                                            
t648      lua_State *L = lua_newstate(l_alloc, NULL);
Call took 0.4028 ms
(gdb) ti
lua_newstate (f=0x7ffff773dbdf <l_alloc>, ud=0x0) at /home/evadeflow/projects/info4/can-daemon/_build/lua-src/src/lstate.c:147
147   void *l = (*f)(ud, NULL, 0, state_size(LG));
Call took: 0.1777 ms
(gdb) ti
l_alloc (ud=0x0, ptr=0x0, osize=0, nsize=616) at /home/evadeflow/projects/info4/can-daemon/_build/lua-src/src/lauxlib.c:630
630   if (nsize == 0) { 
Call took 0.0028 ms
(gdb) ti
635     return realloc(ptr, nsize);
Call took 0.0011 ms
(gdb)

不如gprof准确,但如果您只是想大致了解每一步相对于其他人的步骤,那么很多就更容易了。

答案 1 :(得分:0)

只需使用合适的工具即可完成正确的工作。使用sysprof等分析工具。

已经看到一些improvements in the version >= 3.20