目录
一、多种方式执行代码
是否预分配空间,使用不同的赋值方法都会影响率,下面测试一下
1、声明变量,使用pushback
2、声明变量,使用数组下标 (错误用法)
3、声明变量同时分配空间,使用pushback
4、声明变量同时分配空间,使用数组下标
#include<vector>
#include<time.h>
#include <iostream>
using namespace std;
const static int max = 1000000;
//1、声明变量,使用pushback
void test01()
{
vector<int> vec;
clock_t startTime = clock();
for (int i = 0; i < max ; i++)
{
vec.push_back(i);
}
clock_t endTime = clock();
cout << "The test01 time is: " << (double)(endTime - startTime) << "ms" << endl;
}
// 2、声明变量,使用数组下标 错误用法!!!
// 3、声明变量同时分配空间,使用pushback
void test03()
{
vector<int> vec(max);
clock_t startTime = clock();
for (int i = 0; i < max ; i++)
{
vec.push_back(i);
}
clock_t endTime = clock();
cout << "The test03 time is: " << (double)(endTime - startTime) << "ms" << endl;
}
// 4、声明变量同时分配空间,使用数组下标
void test04()
{
vector<int> vec(max);
clock_t startTime = clock();
for (int i = 0; i < max ; i++)
{
vec[i] = i;
}
clock_t endTime = clock();
cout << "The test04 time is: " << (double)(endTime - startTime) << "ms" << endl;
}
void main() {
test01();
//test02();
test03();
test04();
system("pause");
}
二、执行效率对比
The test01 time is: 613ms
The test03 time is: 573ms
The test04 time is: 46ms
三、总结
多次执行代码,发现vector预分配空间可以少量提升效率,使用数组下标赋值可以极大地提高效率