boost智能指针的性能测试

来源:互联网 发布:ubuntu mate 输入法 编辑:程序博客网 时间:2024/05/01 18:51
   智能指针为内存管理带来了挺大的便利,不过相比传统指针到底慢了多少,是本文要探讨的。
   首先上测试代码
====================================================
#include <iostream>
#include <ctime>
#include <sys/timeb.h>
#include<boost/shared_array.hpp>

using namespace std;

time_t getms()
{
    timebtb;
   ftime(&tb);
    return(int)(tb.time*1000 + tb.millitm);
}

int main()
{
    int times =1000000000;
    {
       int* p = newint[100];
       time_toldtime = getms();
       for (int i =0; i < times; ++ i)
       {
          int* a =p;   
          a[0] =i;         
       }
       time_tnewtime = getms();
       cout<< (newtime - oldtime)<< endl;
       delete[]p;
    }
    {
      boost::shared_array<int> p(newint[100]);
       time_toldtime = getms();
       for (int i =0; i < times; ++ i)
       {
         boost::shared_array<int> a =p;    // copyconstructor
          a[0] =i;                   //visit
       }
       time_tnewtime = getms();
       cout<< (newtime - oldtime)<< endl;
    }
    {
      boost::shared_array<int> p(newint[100]);
       time_toldtime = getms();
       for (int i =0; i < times; ++ i)
       {
         boost::shared_array<int> a =p;    // copyconstructor         
       }
       time_tnewtime = getms();
       cout<< (newtime - oldtime)<< endl;
    }
    {
      boost::shared_array<int> p(newint[100]);
       time_toldtime = getms();
      boost::shared_array<int> a;
       for (int i =0; i < times; ++ i)
       {
          a =p;    //assign         
       }
       time_tnewtime = getms();
       cout<< (newtime - oldtime)<< endl;
    }
    {
      boost::shared_array<int> p(newint[100]);
       time_toldtime = getms();
      boost::shared_array<int> a = p;
       for (int i =0; i < times; ++ i)
       {
          a[0] =i;    //visit         
       }
       time_tnewtime = getms();
       cout<< (newtime - oldtime)<< endl;
    }

    return0;
}

==========================================================
   测试次数是10亿次。
   在windows下VS2008 Release版本测试结果:
688   
12929
12945  // 拷贝构造函数比较耗时,比原始指针慢大概20倍
2048   // 赋值耗时大概是原始指针的3倍
688    //访问耗时和原始指针速度差不多
    在Linux下g++4.1.2默认选项测试结果(两台主机硬件差别很大,不能直接对比):
4023
94694
84130
12270
7071
   这个测试要小心编译器的优化,不然测试的结果会比较奇怪。
   测试结论:智能指针的构造代价比较高(但是还是挺快的,每秒千万-近亿次),赋值和访问效率很高,比原始指针慢没多少。几倍的代价貌似昂贵,其实没必要太担心。智能指针省心啊。满地优化的做法并不可取。还是要doright再do fast。



0 0