• [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 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没啥差别.....

  • 相关阅读:
    jquery文本折叠
    物理小词典
    程序员的十层楼
    各种语言的hello world
    读书遇到的一些概念
    银行业务一些概念
    mysql 基本操作
    oracle 基本操作
    maven 基本操作
    ubuntu JavaWeb环境搭建
  • 原文地址:https://www.cnblogs.com/egmkang/p/2757725.html
Copyright © 2020-2023  润新知