为什么它看起来像的boost :: shared_ptr的结构越来越慢? [英] Why does it look like boost::shared_ptr constructions are getting slower?
问题描述
我有升压shared_ptr的一个问题。在循环智能指针的初始化时间是在第一次迭代后增加。
第一次迭代需要40毫秒。每隔一个循环大约需要400毫秒。
我不知道为什么会发生。我查了一下,有没有内存泄漏和所有析构函数被调用。有没有人有这种情况的解决方案?
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。然而,当我使用了boost :: ptr_vector,时间没有增加(但仅在调试版本:))。
PS. However, when I use the boost::ptr_vector, the time is not increased( but only in debug version :) ).
请参阅例如:
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;
}
推荐答案
时钟()
是一个可怕的时间计数器。你可以勉强算与毫秒。使用monotic_clock或get_time_of_day。或者QueryPerformanceCounter的,如果你是在Windows上。
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.
接下来,这个测试是不是测试shared_ptr的施工时间,它是测量对象大多 A
分配时间。还有在分配的shared_ptr
本身存储引用计数。
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.
使用 make_shared
功能(而不是的shared_ptr(新A)
)加速这一切,靠的因素2。
use make_shared
function (instead of shared_ptr(new A)
) to accelerate all this, by a factor of about 2.
这篇关于为什么它看起来像的boost :: shared_ptr的结构越来越慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!