歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++的性能檢測

C++的性能檢測

日期:2017/3/1 10:05:13   编辑:Linux編程

C++程序,性能檢測十分重要,尤其是在調優的時候,發現程序運行的熱點有助於分析。

下面介紹一下我經常用的性能檢測方法。

首先,先貼出要測試程序的源碼:

#include <iostream>
#include <map>
#include <vector>
#include <time.h>
#include <stdlib.h>
using namespace std;

#define MaxLen 100
#define MaxNum 10000
typedef struct _Key
{
_Key(int *p, int l)
{
len_ = l;
for(int i = 0; i < l; ++i)
p_[i] = p[i];
}
int p_[MaxLen];
int len_;
}Key;
typedef struct _KeyCmp
{
bool operator()(const Key &ls, const Key &rs)
{
if(ls.len_ == rs.len_)
{
for(int i = 0; i < ls.len_; ++i)
return ls.p_[i] < rs.p_[i];
return false;
}
else
return ls.len_ < rs.len_;
}
}KeyCmp;
typedef std::map<Key, vector<int> *, KeyCmp> MyMap;

int main()
{
MyMap *mymap = new MyMap();
vector<int> *sum_vec;
const Key *key;
int len;
int p[MaxLen];
srand( unsigned(time(NULL)));
for(int c = 0; c < MaxNum; ++c)
{
len = rand() % MaxLen + 1;
int sum = 0;
for(int i = 0; i < len; ++i)
{
p[i] = rand() % MaxNum;
sum += p[i];
}
key = new Key(p, len);
sum_vec = new vector<int>();
sum_vec->push_back(sum);
mymap->insert(make_pair(*key, sum_vec));
delete key;
}
for(MyMap::iterator it = mymap->begin(); it != mymap->end(); ++it)
{
delete it->second;
}
delete mymap;
return 0;
}

因為後面打算寫一篇關於C++庫中各種map用法的總結,見 http://www.linuxidc.com/Linux/2012-12/76127.htm,所以這裡先用map練練手,這裡完成的就是一個整數求和的程序。

常用的性能檢測方法是使用grpof 或使用valgrind 兩種方法。

這兩種方法都要求程序在編譯時使用-pg -g參數;

都會用到gprof2dot.py這個程序,gprof2dot.py程序用於將性能分析結果轉化為dot文件。

dot是一種編寫繪圖腳本的語言,它屬於graphviz軟件,是一群牛人開發的。可以去這裡看看。

言規正轉,使用gprof查看性能分析結果,過程如下:

***@Ubuntu:~/Performance$ g++ -pg -g -o mt map_test.cpp
***@ubuntu:~/Performance$ ./mt
***@ubuntu:~/Performance$ ls
gmon.out gprof2dot.py map_test.cpp mt
***@ubuntu:~/Performance$ gprof ./mt > prof.log
***@ubuntu:~/Performance$ ls
gmon.out gprof2dot.py map_test.cpp mt prof.log
***@ubuntu:~/Performance$ python gprof2dot.py -n0.5 -s prof.log > gprof.dot
***@ubuntu:~/Performance$ xdot gprof.dot
***@ubuntu:~/Performance$ dot -Tpng gprof.dot -o gprof.png

Copyright © Linux教程網 All Rights Reserved