[C++11]shared_ptr效率比较
生活随笔
收集整理的這篇文章主要介紹了
[C++11]shared_ptr效率比较
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我實現的網絡庫中使用了C++11中的shared_ptr. 昨天做profile,發現很多CPU都消耗在shared_ptr上,所以打算看看shared_ptr的效率如何.
實驗是這樣的,弄一個臨時的shared_ptr,然后不停的拷貝,拷貝100W次,看消耗多長時間.實驗對象是gcc 4.6.2和clang 3.1(libc++).最后輸出各自消耗的時間,編譯選項,O0和O2.
上代碼:
#include <thread> #include <memory> #include <unistd.h> #include <iostream> #include <sys/time.h>long GetMillionSecond() {timeval val;::gettimeofday(&val, NULL); return val.tv_sec * 1000 + val.tv_usec / 1000; }int main() { #ifdef THREADint terminal = false;std::thread t([&]{while(!terminal) ::usleep(1000*1000);}); #endiflong begin_time = GetMillionSecond();std::shared_ptr<int> p(new int);for(int i = 0; i < 100*10000; ++i){std::shared_ptr<int> a = p;*a = i;}long end_time = GetMillionSecond(); #ifdef THREADterminal = true;t.join(); #endifstd::cout << *p << std::endl;std::cout << end_time - begin_time << "ms" << std::endl;return 0; }測試結果:
| 編譯器/優化選項 | -O0(單位ms) | -O2(單位ms) |
| clang | 44~49 | 37~39 |
| clang thread | 40~49 | 31~39 |
| gcc | 85~92 | 26~31 |
| gcc thread | 87~92 | 28~33 |
不太清楚gcc 4.6.2的libstdc++里面有沒有對單線程進行優化,4.7里面肯定優化了.明天在gcc 4.7上面再試試.
可以看到,開啟優化選項,對兩個實現,都有影響,gcc的優化能力還是比較強.
shared_ptr的效率還好.只是我當時服務器測試,沒有開啟優化選項,所以100W個消息,拷貝兩三次的話,還是有一點吃緊.
PS:
gcc 4.7的優化,好像跟4.6沒啥差別.....
總結
以上是生活随笔為你收集整理的[C++11]shared_ptr效率比较的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Boost】系列02:内存管理之sco
- 下一篇: QT中在终端下写个小例子