gdb:利用break和command计算函数执行时间

gdb:利用断点break和command计算函数执行时间

1. 启动 GDB 并自动执行 gdbcmd 中的命令

gdb --command 选项允许你在启动 GDB 时自动执行一个命令文件中的命令序列。

$ gdb --command=gdbcmd testapp
  • --command=<command_file>:指定包含 GDB 命令的文件。本例中为gdbcmd文件。
  • [program]:指定要调试的程序。本例中为testapp程序。

gdbcmd脚本内容如下:

set pagination off
set breakpoint pending on
set logging file gdb.out
set logging on
break main
run
  • set pagination off

    • 关闭分页功能,使得输出不会被分页显示(即不会暂停等待用户输入以继续显示更多内容)。
  • set breakpoint pending on

    • 允许设置尚未加载的符号的断点。如果某个符号当前不可用(例如动态加载的库),GDB 会将其视为待处理断点,并在符号可用时自动设置断点。
  • set logging file gdb.out

    • 设置日志文件的名称为 gdb.out,所有后续的 GDB 输出都将记录到这个文件中。
  • set logging on

    • 启动日志记录功能,将所有输出写入之前指定的日志文件。

2. 找到函数的入口地址并设置断点

2.1 通过info functions找到函数地址

(gdb) info functions QQmlApplicationEngine::load(QUrl const&)
All functions matching regular expression "QQmlApplicationEngine::load(QUrl const&)":

Non-debugging symbols:
0x0000007ff6b502a8  QQmlApplicationEngine::load(QUrl const&)
  • 函数名:QQmlApplicationEngine::load(QUrl const&)
  • 地址:0x0000007ff6b502a8

2.2 设置断点及断点触发后执行的命令

(gdb) break *0x0000007ff6b502a8
Breakpoint 2 at 0x7ff6b502a8
(gdb) command 2
Type commands for breakpoint(s) 2, one per line.
End with a line saying just "end".
>shell cat /proc/uptime
>continue
>end
  • 通过break *0x0000007ff6b502a8新增断点2
  • 通过command 2为断点2设置断点触发后执行的命令,打印/proc/uptime的值

3. 找到函数的返回地址并设置断点

3.1 通过反汇编找到函数返回地址

在这里插入图片描述

  • disassemble *0x0000007ff6b502a8 执行反汇编
  • ret 指令代表返回,函数返回地址为0x0000007ff6b5032c

3.2 设置断点及断点触发后执行的命令

(gdb) break *0x0000007ff6b5032c
Breakpoint 3 at 0x7ff6b5032c
(gdb) command 3
Type commands for breakpoint(s) 3, one per line.
End with a line saying just "end".
>shell cat /proc/uptime
>continue
>end
  • 通过break *0x0000007ff6b5032c新增断点3
  • 通过command 3为断点2设置断点触发后执行的命令,打印/proc/uptime的值

4. 继续执行并根据打印计算函数执行时间

4.1 continue继续执行

(gdb) continue
Thread 1 "testapp" hit Breakpoint 2, 0x0000007ff6b502a8 in QQmlApplicationEngine::load(QUrl const&) () from /opt/qt5.15.2-install/lib/libQt5Qml.so.5
1829.78 6492.12

Thread 1 "testapp" hit Breakpoint 3, 0x0000007ff6b5032c in QQmlApplicationEngine::load(QUrl const&) () from /opt/qt5.15.2-install/lib/libQt5Qml.so.5
1867.98 6567.00

4.2 计算函数执行时间

/proc/uptime文件提供了系统运行时间和空闲时间的信息。第一列是系统运行时间(以秒为单位),第二列是系统空闲时间。

函数入口时间戳:1829.78
函数出口时间戳:1867.98
函数执行时间:1867.98 - 1829.78 = 38.2秒

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值