问题
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