Why does it look like boost::shared_ptr constructions are getting slower?

时光毁灭记忆、已成空白 提交于 2020-01-17 03:04:37

问题


I have a problem with boost shared_ptr. The initialization time of the smart pointer in the cycle is increased after the first iteration. The first iteration takes 40 msec. Every other iteration takes about 400 msec. I have no idea why it happens. I checked and there are no memory leaks and all destructors are called. Does anyone have a solution of this case?

PS. However, when I use the boost::ptr_vector, the time is not increased( but only in debug version :) ).

See example:

class A;
typedef boost::shared_ptr<A> A_ptr;
class A
{
public:
  A(){}
  A_ptr add(A* new_A)
  {
    A_ptr new_A_ptr( new_A );
    children.push_back(new_A_ptr);
    return new_A_ptr;
  }
  ~A(){}
  vector<A_ptr> children;
};

void test()
{
   A_ptr root_ptr( new A() );
   for (int k=0; k<200; k++)
   {
        A_ptr sub_ptr = root_ptr->add( new A() );
        for (int l=0; l<100; l++) sub_ptr->add( new A() );
   }
};

int main()
{
  for(int i=0; i<10; i++)
  {
    unsigned t = clock();    
    test();
    std::cout<<"elapsed: "<<clock()-t<<std::endl;
  }

  return 0;
}


回答1:


clock() is a terrible time counter. you can barely count milliseconds with that. use monotic_clock or get_time_of_day. Or QueryPerformanceCounter if you are on windows.

Next, this test is not testing shared_ptr construction time, it is measuring mostly object A allocation time. There is also an allocation in the shared_ptr itself to store the ref count.

use make_shared function (instead of shared_ptr(new A)) to accelerate all this, by a factor of about 2.



来源:https://stackoverflow.com/questions/5713329/why-does-it-look-like-boostshared-ptr-constructions-are-getting-slower

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!