C++ 虚函数耗时性能优化

本测试用例主要是小破站的up主寒海明灯所提供,在此表示感谢,作者自己作为学习收集。

示例:程序主要讲解的是在vector容器中存储A的对象以及A的派生对象,在对容器里面的对象的虚函数调用时耗时的统计以及性能的优化。

优化的方法:对vector里面的对象进行排序。

#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>

struct A
{
     virtual int foo()
     {
        return i;  
     }
     int i;
};


struct B:A
{
    virtual int foo() override
    {
        return A::i+1;
    }
};

std::vector<A*> gen_data(int N)
{
   std::vector<A*> va;
   for(int i = 0; i < N; i++)
   {
           if(rand() & 1)
           {
                va.push_back(new A());
           }
           else
           {
                va.push_back(new B());
           }
           va.back()->i = rand();
   }
   
   std::random_shuffle(va.begin(),va.end());
   return va;
}

 int test(int M,std::vector<A*> & va)
 {
   std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
   int sum =0;
   for(int i = 0; i < M; i++)
   {
         for(size_t j = 0; j < va.size();j++)
         {
              sum += va[j]->foo();
         }
   }
   std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now();
   
   std::cout << "elapsed milliseconds: "<< std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << std::endl;
   
   return sum;
  }
  
  int main()
  {
      srand(12345);
      const int N = 10000;
      std::vector<A*> va = gen_data(N);
      const int M = 10000;
      int sum = test(M,va);
      std::sort(va.begin(),va.end(),[](const A* a,const A*b) {return typeid(*a).before(typeid(*b));});
      sum += test(M,va);
      std::cout << "sum =" << sum << std::endl;
      return 0;
  }

实现结果:耗时从656 降低到 211

使用场景:在观察模式中可用到此类优化,一个条件触发后,对容器中所有注册的虚函数进行调用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水火汪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值