當前位置:才華齋>IT認證>Linux認證>

Linux下程式的Profile工具

Linux認證 閱讀(1.59W)

我們在寫嵌入式程式時,通常需要對程式的效能進行分析,以便程式能夠更快更好地執行,達到實時(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();