Why does it look like this: boost :: shared_ptr constructions slow down?

I have a problem with boost shared_ptr. The initialization time of a smart pointer in a loop increases after the first iteration. The first iteration takes 40 ms. Each other iteration takes about 400 ms. I have no idea why this is happening. I checked and there are no memory leaks, and all destructors are called. Does anyone have a solution to this case?

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

See an 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; } 

0
source share
1 answer

clock() is a terrible time counter. you can hardly count milliseconds. use monotic_clock or get_time_of_day. Or QueryPerformanceCounter if you are in windows.

Further, this test does not test the construction time of shared_ptr, it measures mainly the time of placing object A There is also an allocation in shared_ptr itself for storing the number of links.

use the make_shared function (instead of shared_ptr(new A) ) to speed it all up, about 2 times.

0
source

All Articles