class X {
public:
std::string name;
int age;
long references;
X(string n, int a) : references(0), name(n), age(a) {}
};
inline void intrusive_ptr_add_ref(X* x){
++x->references;
}
inline void intrusive_ptr_release(X* x){
if(--x->references == 0)
delete x;
}
int _tmain(int argc, _TCHAR* argv[])
{
time_t t=clock();
size_t rounds=1000000;
for(size_t i=0; i<rounds; i++)
{
intrusive_ptr<X> myX(new X("Michael",40));
myX->age++;
}
cout << "Time taken to generate " << rounds << " of intrusive_ptr is "
<< clock()-t << endl;
t=clock();
for(size_t i=0; i<rounds; i++)
{
boost::shared_ptr<X> myX(new X("Michael",40));
myX->age++;
}
cout << "Time taken to generate " << rounds << " of shared_ptr is "
<< clock()-t << endl;
t=clock();
for(size_t i=0; i<rounds; i++)
{
std::shared_ptr<X> myX(new X("Michael",40));
myX->age++;
}
cout << "Time taken to generate " << rounds << " of Microsoft shared_ptr is "
<< clock()-t << endl;
t=clock();
for(size_t i=0; i<rounds; i++)
{
boost::shared_ptr<X> myX=boost::make_shared<X>("Michael",40);
myX->age++;
}
cout << "Time taken to generate " << rounds << " of shared_ptr using make_shared is "
<< clock()-t << endl;
t=clock();
for(size_t i=0; i<rounds; i++)
{
std::shared_ptr<X> myX=std::make_shared<X>("Michael",40);
myX->age++;
}
cout << "Time taken to generate " << rounds << " of Microsoft shared_ptr using make_shared is "
<< clock()-t << endl;
_getche();
return 0;
}
我在发布模式下使用 vs2010 得到了以下结果。
生成 1000000 个 intrusive_ptr 所需的时间为 116 生成 1000000 个 shared_ptr 所需的时间为 175 生成 1000000 个 Microsoft shared_ptr 所需的时间为 182 使用 make_shared 生成 1000000 个 shared_ptr 所需的时间为 176 使用 make_shared 生成 1000000 个 Microsoft shared_ptr 所需的时间为120
似乎 intrusive_ptr 是最快的,但似乎 MS 使用 make_shared 函数对 shared_ptr 也做得很好。但是为什么 boost make_shared 的性能不如 MS 版本?有人做过类似的测试吗?我的测试有什么问题或者我没有考虑到什么?