下面的測試顯示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%)
回復 更多評論