再谈动态数组与向量存储速度

来源:互联网 发布:gcc下载 windows 编辑:程序博客网 时间:2024/06/15 12:25

实验的是20000000个float数据分别在动态数组和向量上的存取时间,

动态数组上的时间是281ms,向量上的时间是17078ms

二者时间相差约60倍。

结论:在耗时情况下,选用数组省时间


#include <vector>
#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
time_t start, ends;
clock_t cstart,cends;
start=time(NULL);
cstart=clock();
float* fary=new float [20000000];
for (int i=0;i<20000000;i++)
fary[i]=2.0;
delete fary;
fary=NULL;
ends=time(NULL);
cends=clock();
cout << "时间差:" << difftime(ends,start) << endl;
cout << "Clock时间差:" << cends-cstart << endl;

start=time(NULL);
cstart=clock();
vector<float> fvec;
for (i=0;i<20000000;i++)
fvec.push_back(2.0);
ends=time(NULL);
cends=clock();
cout << "时间差:" << difftime(ends,start) << endl;
cout << "Clock时间差:" << cends-cstart << endl;

return 0;
}