[C++11]shared_ptr效率比較

來源:互聯網
上載者:User

  我實現的網路程式庫中使用了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 THREAD  int terminal = false;  std::thread t(      [&]{      while(!terminal)         ::usleep(1000*1000);      });#endif  long 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 THREAD  terminal = true;  t.join();#endif  std::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沒啥差別.....

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.