gprof工作方式
在使用gcc編譯時指定-pg選項,編譯器在用戶代碼中插入性能測試代碼。
gprof簡單應用實例
main.c
#include <stdio.h> #include "lib.h" int main(void) { func1(20); func2(100); return 0; }
lib.h
#ifndef LIB_H #define LIB_H void func1(int i); void func2(int i); #endif /* LIB_H */
lib.c
#include <stdio.h> #include "lib.h" void func1(int i) { while (i--) printf("func1(): %d\n", i); } void func2(int i) { while (i--) printf("func2(): %d\n", i); }
Makefile
CFLAGS += -pg objs = $(patsubst %.c,%.o,$(wildcard *.c)) prog: $(objs) gcc -pg -o $@ $^ clean: -rm -f prog $(objs)
在命令行運行make編譯代碼,產生prog文件。輸入./prog運行文件,產生一個輸出文件gmon.out。之後
用工具gprof分析該輸出文件分析程序的運行情況,並依據這些分析得出的數據優化程序。
運行 gprof prog gmon.out > gprofrslt.txt 分析輸出文件得到如下結果(節選部分內容)。可根據
傳遞給gprof不同的參數得出不同方面性能考量的輸出。
Flat profile: Each sample counts as 0.01 seconds. no time accumulated % cumulative self self total time seconds seconds calls Ts/call Ts/call name 0.00 0.00 0.00 1 0.00 0.00 func1 0.00 0.00 0.00 1 0.00 0.00 func2
具體輸出的含義可參考gprof幫助文檔。
3. grof缺點
對多線程、內核態支持不好。只統計佔用的CPU時間,而陷入睡眠態的時間不做統計,可結合time命令等
其他工具來優化性能。
4. gprof文檔