gperftools是google出品的一个性能分析工具,相关介绍可见:https://github.com/gperftools/gperftools/wikigit
gperftools在64位系统上须要unwind库的支持,因此须要先安装libunwind,并且对版本有了要求github
下载:https://github.com/libunwind/libunwind/releases 函数
解压后 ./configure CFLAGS=-U_FORTRIFY_SOURCE CFLAGS=-fPIC --prefix=/home/yourpath ; sudo make ; sudo make install ;工具
下载:https://github.com/gperftools/gperftools/releases 同上 性能
安装过程当中可能有各类 error,make[3]: *** [install-libLTLIBRARIES] Error 1 可忽略。测试
图形工具graphvizgoogle
一、能够直接调用提供的API(在须要测试的代码的先后分别调用ProfilerStart()和ProfilerStop()) spa
一直运行的程序因为不能正常退出,因此不能采用上面的方法。咱们能够用信号量来开启/关闭性能分析code
#include <gperftools/profiler.h> #include <stdlib.h> #include <stdio.h> #include <signal.h> void gprofStartAndStop(int signum) { static int isStarted = 0; if (signum != SIGUSR1) return; //经过isStarted标记将来控制第一次收到信号量开启性能分析,第二次收到关闭性能分析。 if (!isStarted){ isStarted = 1; ProfilerStart("test.prof"); printf("ProfilerStart success\n"); }else{ ProfilerStop(); printf("ProfilerStop success\n"); } } void f() { int i; for (i=0; i<1024*1024; ++i) { char *p = (char*)malloc(1024*1024); free(p); } } int main() { signal(SIGUSR1, gprofStartAndStop); while(1){ printf("call f\n"); f(); sleep(1);//为了防止死循环,致使信号处理函数得不到调度 } return 0; }
用top命令查看进程的PID
kill -s SIGUSR1 PID //第一次运行命令启动性能分析
kill -s SIGUSR1 PID //再次运行命令关闭性能分析,产生test.profblog
对于一个函数的CPU使用时间分析,分为两个部分:
1.整个函数消耗的CPU时间,包括函数内部其余函数调用所消耗的CPU时间
2.不包含内部其余函数调用所消耗的CPU时间(内联函数除外)
pprof --text ./demo my.prof > profile.txt
关于文本风格输出结果,每行包含6列数据,依次为:
列号 | 说明 |
1 | 分析样本数量(不包含其余函数调用),样本数量至关于消耗的CPU时间 |
2 | 分析样本百分比(不包含其余函数调用) |
3 | 目前为止的分析样本百分比(不包含其余函数调用) |
4 | 分析样本数量(包含其余函数调用) |
5 | 分析样本百分比(包含其余函数调用) |
6 | 函数名 |
整个函数消耗的CPU时间至关于包括函数内部其余函数调用所消耗的CPU时间
pprof --pdf ./demo my.prof > profile.pdf
1.节点
每一个节点表明一个函数,节点数据格式:
Class Name Method Name local (percentage) of cumulative (percentage) |
local时间是函数直接执行的指令所消耗的CPU时间(包括内联函数);性能分析经过抽样方法完成,默认是1秒100个样本,一个样本是10毫秒,即时间单位是10毫秒;
cumulative时间是local时间与其余函数调用的总和;若是cumulative时间与local时间相同,则不打印cumulative时间项。
有向边:调用者指向被调用者,有向边上的时间表示被调用者所消耗的CPU时间
二、能够以静态连接方式进行连接并在执行的时候经过环境变量指定分析文件的输出路径:
http://blog.51cto.com/wulingdong/2043898