我正在使用 gdb (gtk) 调试 C 库。
有一个功能太慢了。我试图找出函数的哪一部分导致了延迟。
我知道一种选择可能是插入手动代码/重新编译到基准代码段,但是有没有办法获取在 gdb 中执行单个步骤 's' 所花费的时间?
为了快速进行分析,您可以将此片段放入您的
~/.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那么准确,但是如果您只是想粗略地了解每个步骤相对于其他步骤花费的时间,那么更容易。