手机版
你好,游客 登录 注册
背景:
阅读新闻

C++的性能检测

[日期:2012-12-15] 来源:Linux社区  作者:xinzhangyanxiang [字体:大 中 小]

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

linux
相关资讯       C++ 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款