下面的测试显示shared_ptr相对于使用原始指针会慢上很多(2-4倍),主要是来自引用计数及其带来的指针对象的创建销毁时间,下面的测试代码都是指针创建及传递操作:
#include <windows.h>
#include <cassert>
#include <iostream>
#include <string>
#include <boost/shared_ptr.hpp>
typedef int type;
typedef type* raw_ptr_type;
typedef boost::shared_ptr<type> shared_ptr_type;
template<typename T>
void use(T ptr)
{
T ptr1 = ptr;
T ptr2 = ptr;
T ptr3 = ptr;
}
int main(int argc, char* argv[])
{
size_t count = 500000;
if(argc > 1)
count = atoi(argv[1]);
DWORD oldtime, shared_ptr_time, raw_ptr_time;
{
oldtime = GetTickCount();
for (size_t i = 0; i < count ; ++i)
{
raw_ptr_type ptr(new type);
use(ptr);
delete ptr;
}
raw_ptr_time = GetTickCount() - oldtime;
}
{
oldtime = GetTickCount();
for (size_t i = 0; i < count ; ++i)
{
shared_ptr_type ptr(new type);
use(ptr);
}
shared_ptr_time = GetTickCount() - oldtime;
}
assert(raw_ptr_time <= shared_ptr_time);
std::cout << "count(" << count << ") raw_ptr(" << raw_ptr_time << " ms) shared_ptr(" << shared_ptr_time << " ms) diff(+" << shared_ptr_time - raw_ptr_time << " ms, +" << double(shared_ptr_time - raw_ptr_time)/double(raw_ptr_time)*100 << "%)"<< std::endl;
return EXIT_SUCCESS;
}
vc2008下 Release 禁用优化的三次执行:
count(500000) raw_ptr(110 ms) shared_ptr(591 ms) diff(+481 ms, +437.273%)
count(500000) raw_ptr(110 ms) shared_ptr(471 ms) diff(+361 ms, +328.182%)
count(500000) raw_ptr(120 ms) shared_ptr(471 ms) diff(+351 ms, +292.5%)
vc2008下 Release 完全优化的三次执行:
count(500000) raw_ptr(111 ms) shared_ptr(330 ms) diff(+219 ms, +197.297%)
count(500000) raw_ptr(100 ms) shared_ptr(331 ms) diff(+231 ms, +231%)
count(500000) raw_ptr(110 ms) shared_ptr(351 ms) diff(+241 ms, +219.091%)
回复 更多评论