C++的性能检测
C++的性能检测
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用法的总结,见 ,所以这里先用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
|
评论暂时关闭