使用pprof監測C/C++程序

##1、安裝 到 https://github.com/gperftools/gperftools 下載,而後:html

$ sudo apt-get install autoconf
$ sudo apt-get install automake
$ sudo apt-get install libtool  
$ ./autogen.sh
$ ./configure
$ make
$ sudo  make install
$ su root
# echo /usr/local/lib > /etc/ld.so.conf.d/libtcmalloc.conf
# exit
$  sudo ldconfig

2、檢測內存的使用

#include <iostream>
#include <unistd.h>
using namespace std;

class Person {
private:
    string name;
public:
    void setName(string name) {
        this->name = name;
    }

    const string& getName() {
        return this->name;
    }
};

int main() {
    Person *someone;
    for(int i=0; i<10; ++i) {
        someone = new Person;
        someone->setName("Li Ming"); 
        cout << someone->getName() << endl;
        // sleep(2);
    }
}
$ g++ example.cpp -ltcmalloc
$ HEAPPROFILE=test   ./a.out

程序運行結束後,當前目錄會出現 test.0001.heap文件。node

生成pdf:ios

$ pprof --pdf a.out test.0001.heap > test.pdf

輸入圖片說明

3、查看內存泄漏

$ export PPROF_PATH=/usr/local/bin/pprof
$ HEAPCHECK=normal ./a.out              
WARNING: Perftools heap leak checker is active -- Performance may suffer
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Have memory regions w/o callers: might report false leaks
Leak check _main_ detected leaks of 400 bytes in 20 objects
The 2 largest leaks:
Using local file ./a.out.
Leak of 320 bytes in 10 objects allocated from:
	@ 7fb33ee69249 std::string::_Rep::_S_create
	@ 7fb33ee6a971 std::string::_S_construct
	@ 7fb33ee6ad88 std::basic_string::basic_string
	@ 400d8e main
	@ 7fb33e7f5f45 __libc_start_main
	@ 400c79 _start
Leak of 80 bytes in 10 objects allocated from:
	@ 400d5e main
	@ 7fb33e7f5f45 __libc_start_main
	@ 400c79 _start


If the preceding stack traces are not enough to find the leaks, try running THIS shell command:

pprof ./a.out "/tmp/a.out.31217._main_-end.heap" --inuse_objects --lines --heapcheck  --edgefraction=1e-10 --nodefraction=1e-10 --gv

If you are still puzzled about why the leaks are there, try rerunning this program with HEAP_CHECK_TEST_POINTER_ALIGNMENT=1 and/or with HEAP_CHECK_MAX_POINTER_OFFSET=-1
If the leak report occurs in a small fraction of runs, try running with TCMALLOC_MAX_FREE_QUEUE_SIZE of few hundred MB or with TCMALLOC_RECLAIM_MEMORY=false, it might help find leaks more repeatab
Exiting with error code (instead of crashing) because of whole-program memory leaks
g++ example03.cpp -ltcmalloc
HEAPPROFILE=test   ./a.out

錯誤解決

1、`sh: 1: dot: not found`git

sudo apt-get install graphviz

二、"gv": No such filegithub

參考

tcmalloc安裝,使用以及解析(一)
error while loading shared libraries: xxx.so.x"錯誤的緣由和解決辦法 shell

其餘

用gperftools對C/C++程序進行profile緩存

https://github.com/gperftools/gperftools工具

關於gperftoolsui

Google CPU Profiler使用指南及小工具this

TCMalloc:線程緩存的Malloc

TCMalloc小記

相關文章
相關標籤/搜索