Gcc中使用profile工具优化代码

本文介绍了如何在 Mingw32环境下利用GCC的profile工具进行代码优化。通过示例代码展示了如何编译并执行程序,生成gmon.out日志文件,然后使用gprof分析调用次数和调用路径,帮助程序员了解函数调用情况,从而进行性能优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Gcc 中使用 profile 工具优化代码

 

作者: wulong710

目的,查询代码中各个函数被调用了几次、在何处被调用。方便程序员对代码进行优化。

环境为 mingw32

 

编辑如下代码 :

#include "iostream"

#include "stdlib.h"

using namespace std;

 

int func_ten ()

{

       _sleep (500);

       cout << "exect func ten" <<endl;

       return 0;

}

 

int func_once ()

{

 

       _sleep (300);

       cout << "exect func once" <<endl;

       func_ten ();

 

       return 0;

}

 

int main(void)

{

       for (int i = 0; i < 10; i++)

              func_ten ();

 

       func_once ();

 

       return 0;

}

 

profile 模式编译

$ g++ -Wall -pg -o he test.cpp

 

执行 he.exe 生成 gmon.out 日志

$ ./he.exe

 

执行 gprof 将日志写入 log.txt

$ gprof he.exe > log.txt

 

查看 log.txt

$ vim log.txt

 

结果显示:

func_ten 被调用了 11 次,其中 10 次为 main 所调,一次为 func_once 所调。

func_once main 函数调用一次

 

  %   cumulative   self              self     total           ^M

  time   seconds   seconds    calls  Ts/call  Ts/call  name    ^M

  0.00      0.00     0.00       11     0.00     0.00  func_ten() ^M 

  0.00      0.00     0.00        1     0.00     0.00  func_once() ^M

^

 

index % time    self  children    called     name^M

                0.00    0.00       1/11          func_once() [7]^M

                0.00    0.00      10/11          _main [1240]^M

[4]      0.0    0.00    0.00      11         func_ten() [4]^M

 

-----------------------------------------------^M

                0.00    0.00       1/1           _main [1240]^M

[7]      0.0    0.00    0.00       1         func_once() [7]^M

                0.00    0.00       1/11          func_ten() [4]^M

-----------------------------------------------^M

 

结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值