本测试用例主要是小破站的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
![](https://img-blog.csdnimg.cn/img_convert/f324a810b3ab7f3f801f28b86e648d8f.png)
使用场景:在观察模式中可用到此类优化,一个条件触发后,对容器中所有注册的虚函数进行调用。