code profiling

来源:互联网 发布:互联网职位 知乎 编辑:程序博客网 时间:2024/06/05 17:10

本文基于c/c++。

perf

可以使用perf list列出所有支持的event。perf工具支持硬件和软件事件,硬件事件由硬件计数器测量。
常关心的硬件事件如下:

cpu-cycles OR cyclesinstructionscache-referencescache-missesbranch-instructions OR branchesbranch-missesbus-cyclesstalled-cycles-frontend OR idle-cycles-frontendstalled-cycles-backend OR idle-cycles-backendref-cycles

关心的软件事件如下:

cpu-clocktask-clockpage-faults OR faultscontext-switches OR cscpu-migrations OR migrationsminor-faultsmajor-faultsalignment-faultsemulation-faults

测量test_prof程序耗时如下:
这里写图片描述
以上找到的是程序总的耗时。

找到程序中的热点

1.使用perf record获得prof.data性能分析文件。
这里写图片描述
2.使用perf report查看性能分析文件
第一页显示的是分析包含的事件

Available samples                                                                                                                                2K cpu-clock                                                                                                                                    ◆6 faults   

第二页是详细统计
这里写图片描述
从上面可以看到哪个函数耗时较多;
这里写图片描述
从上面可以看到缺页异常开销在什么地方。
也可以使用sudo perf report --stdio将统计信息直接显示在终端上。

perf annotate

可以显示源码和汇编对应的性能分析。

实时监控系统状态

perf top

这里写图片描述

gprof

在编译时需要加上-pg选项,

gcc -Wall -std=c99 -pg test_prof.c -o test_prof然后运行测试程序生成gmon.out./test_prof最后生成详细性能分析gprof test_prof gmon.out > prof_output.txt

生成包括两个部分,一个是程序的耗时,另外一部分是程序调用图关系。

Flat profile:Each sample counts as 0.01 seconds.  %   cumulative   self              self     total            time   seconds   seconds    calls  ms/call  ms/call  name     97.38      0.53     0.53        1   525.84   525.84  func3  3.75      0.55     0.02        1    20.22   546.07  func1  0.00      0.55     0.00        1     0.00   525.84  func2  0.00      0.55     0.00        1     0.00     0.00  func4granularity: each sample hit covers 2 byte(s) for 1.83% of 0.55 secondsindex % time    self  children    called     name                0.02    0.53       1/1           main [2][1]    100.0    0.02    0.53       1         func1 [1]                0.00    0.53       1/1           func2 [3]-----------------------------------------------                                                 <spontaneous>[2]    100.0    0.00    0.55                 main [2]                0.02    0.53       1/1           func1 [1]                0.00    0.00       1/1           func4 [5]-----------------------------------------------                0.00    0.53       1/1           func1 [1][3]     96.3    0.00    0.53       1         func2 [3]                0.53    0.00       1/1           func3 [4]-----------------------------------------------                0.53    0.00       1/1           func2 [3][4]     96.3    0.53    0.00       1         func3 [4]-----------------------------------------------                0.00    0.00       1/1           main [2][5]      0.0    0.00    0.00       1         func4 [5]-----------------------------------------------
原创粉丝点击