Linux下程序的Profile工具

我們在寫嵌入式程序時,通常需要對程序的性能進行分析,以便程序能夠更快更好地運行,達到實時(real-time)的目的。如果程序很大,分析起來就很困難。如果有個工具能夠自動進行程序的性能分析,那就最好了。這裏介紹一種Linux下程序的Profiling工具----GNU profiler。

Linux下程序的Profile工具

  gprof的基本用法:

1. 使用 -pg 選項編譯和鏈接你的應用程序

在gcc編譯程序的時候,加上-pg選項,例如:

gcc -pg -o test test.c

這樣就生成了可執行文件test。如果是大項目,就在makefile裏面修改編譯選項,-pg放在那裏都行。

2. 執行你的應用程序使之生成供gprof 分析的數據

運行剛纔的程序:./test,這樣就生成了一個文件,該文件就包含了profiling的數據。

3. 使用gprof 分析你的應用程序生成的數據

gprof test >

使用上面的命令,gprof就可以分析程序test的性能,將profiling的結果放在文件中,打開就可以看到分析的結果。通過對結果的分析來改進我們的程序,從而達到我們的目的。

GNU gprof是個很不錯的工具,大家寫程序時可以多用用。我現在用gprof來profiling我的程序,把耗時最多的函數或運算找出來,用FPGA芯片實現,從而達到real-time的目的。

  爲gprof編譯程序

在編譯或鏈接源程序的時候在編譯器的命令行參數中加入“-pg”選項,編譯時編譯器會自動在目標代碼中插入用於性能測試的代碼片斷,這些代碼在程序在運行時採集並記錄函數的調用關係和調用次數,以及採集並記錄函數自身執行時間和子函數的調用時間,程序運行結束後,會在程序退出的路徑下生成一個文件。這個文件就是記錄並保存下來的監控數據。可以通過命令行方式的gprof或圖形化的Kprof來解讀這些數據並對程序的性能進行分析。另外,如果想查看庫函數的profiling,需要在編譯是再加入“-lc_p”編譯參數代替“-lc”編譯參數,這樣程序會鏈接libc_p.a庫,纔可以產生庫函數的profiling信息。如果想執行一行一行的profiling,還需要加入“-g”編譯參數。

  例如如下命令行:

gcc -Wall -g -pg -lc_p example.c -o example

  執行gprof

執行如下命令行,即可執行gprof:

gprof OPTIONS EXECUTABLE-FILE BB-DATA [YET-MORE-PROFILE-DATA -FILES...] [> OUTFILE]

  gprof產生的信息

% the percentage of the total running time of the

time program used by this function.

函數使用時間佔所有時間的百分比。

cumulative a running sum of the number of seconds accounted

seconds for by this function and those listed above it.

函數和上列函數累計執行的時間。

self the number of seconds accounted for by this

seconds function alone. This is the major sort for this

listing.

函數本身所執行的時間。

calls the number of times this function was invoked, if

this function is profiled, else blank.

函數被調用的次數

self the average number of milliseconds spent in this

ms/call function per call, if this function is profiled,

else blank.

每一次調用花費在函數的時間microseconds。

total the average number of milliseconds spent in this

ms/call function and its descendents per call, if this

function is profiled, else blank.

每一次調用,花費在函數及其衍生函數的平均時間microseconds。

name the name of the function. This is the minor sort

for this listing. The index shows the location of

the function in the gprof listing. If the index is

in parenthesis it shows where it would appear in

the gprof listing if it were to be printed.

  函數名

  prof 實現原理:

通過在編譯和鏈接你的.程序的時候(使用 -pg 編譯和鏈接選項),gcc 在你應用程序的每個函數中都加入了一個名爲mcount ( or “_mcount” , or “__mcount” , 依賴於編譯器或操作系統)的函數,也就是說你的應用程序裏的每一個函數都會調用mcount, 而mcount 會在內存中保存一張函數調用圖,並通過函數調用堆棧的形式查找子函數和父函數的地址。這張調用圖也保存了所有與函數相關的調用時間、調用次數等等的所有信息。

  Gprof 簡單使用:

讓我們簡單的舉個例子來看看Gprof是如何使用的。

  1.打開linux終端。新建一個test.c文件,並生用-pg 編譯和鏈接該文件。

test.c 文件內容如下:

引文:

#include "stdio.h"

#include "stdlib.h"

void a(){

printf("tt+---call a() functionn");

}

void c(){

printf("tt+---call c() functionn");

}

int b() {

printf("t+--- call b() functionn");

a();

c();

return 0;

}

int main(){

printf(" main() function()n");

b();