#include "..\..\include\stlExample\Containers.h"
#include "..\..\include\stlExample\StopWatch.h"
//#include "StopWatch.h"
#include <iostream>
#include <boost/progress.hpp>
#include <list>
using namespace std;
//vector性能测试
void Containers::vectorPerformanceTest()
{
StopWatch sw; //时间处理类
TestRunAggregater tg; //运行时间
tg.test1 = 0; //微秒
tg.test2 = 0; //毫秒
tg.test3 = 0; //秒
// #1: 通过提前保留vector的大小,避免不必要的重新分配和复制周期。
cout << "\n(1): 通过提前保留vector的大小,避免不必要的重新分配和复制周期";
vector<BigTestStruct> testVector1;
vector<BigTestStruct> testVector2;
BigTestStruct f[ADD_BS];
//控制台进度条
boost::progress_display display(100); //参数为基数
for (int i = 0; i < 100; i++)
{
sw.Restart(); //重置时间
FillVector(testVector1); //添加一个数据结构体
tg.test1 += sw.ElapsedUs(); //微妙
sw.Restart();
//重点:用reserve先储备10000个空间
testVector2.reserve(ADD_BS);
FillVector(testVector2);
tg.test2 += sw.ElapsedUs();
sw.Restart();
shuZhu(f); //数组测试
tg.test3 += sw.ElapsedUs();
testVector1.clear(); //清除内容
testVector1.shrink_to_fit(); //通过释放未使用的内存来减少内存使用
testVector2.clear();
testVector2.shrink_to_fit();
++display; //进度条
}
cout << "\n无预约创建"<<ADD_BS<<" vector,100次结果的平均时间:" << (tg.test1 / 100) << endl;
cout << "reserve预约创建" << ADD_BS << " vector,100次结果平均时间:" << (tg.test2 / 100) << endl;
cout << "数组创建" << ADD_BS << " 数组,100次结果平均时间:" << (tg.test3 / 100) << endl;
tg.Reset();
//#2 使用shrink_to_fit()来释放vector ,别用clear()或erase()清除内容而不释放内存
cout << "\n\n(2)使用shrink_to_fit()来释放vector ,别用clear()或erase()清除内容而不释放内存\n";
FillVector(testVector1);
//capacity返回当前分配的存储中可以保存的元素数
size_t capacity = testVector1
vector效率测试代码
最新推荐文章于 2024-02-01 19:28:36 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)