源代码如下:
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <vector>
#include <array>
#include <iostream>
#include <windows.h>
using namespace std;
#define LOOP 100 * 1000UL
#define TIMES 10 * 1000UL
//typedef double ARR_TYPE;
typedef unsigned int ARR_TYPE;
array<ARR_TYPE, LOOP> stdarr = {0};
vector<ARR_TYPE> vec(LOOP);
ARR_TYPE arr[LOOP];
long size = 0;
int test()
{
DWORD dwTickstart = 0;
DWORD dwTickend = 0;
size = stdarr.size();
dwTickstart = GetTickCount();
for (int k = 0; k < TIMES; k++)
for (unsigned long i = 0; i != size; i++) { stdarr[i] = k; } // for
dwTickend = GetTickCount();
cout << "STD::ARRAY: " << dwTickend-dwTickstart << " microseconds." << endl;
dwTickstart = GetTickCount();
for (int k = 0; k < TIMES; k++)
for (auto &v : stdarr)
{
v = k;
}
dwTickend = GetTickCount();
cout << "STD::ARRAY: auto:" << dwTickend-dwTickstart << " microseconds." << endl;
dwTickstart = GetTickCount();
for (int k = 0; k < TIMES; k++)
for (auto &v : stdarr)
{
v = k;
}
dwTickend = GetTickCount();
cout << "STD::ARRAY: auto:" << dwTickend-dwTickstart << " microseconds." << endl;
//////////////////////////////////////////////////////////////////////////////
dwTickstart = GetTickCount();
size = vec.size();
for (int k = 0; k < TIMES; k++)
for (unsigned long i = 0; i != size; i++) { vec[i] = i; } // for
dwTickend = GetTickCount();
cout << "STD::vector:" << dwTickend-dwTickstart << " microseconds." << endl;
dwTickstart = GetTickCount();
for (int k = 0; k < TIMES; k++)
for (auto &v : vec)
{
//cout << v << endl;
v = k;
}
dwTickend = GetTickCount();
cout << "STD::vector: auto:" << dwTickend-dwTickstart << " microseconds." << endl;
//////////////////////////////////////////////////////////////////////////////
ARR_TYPE arr2[LOOP];
int * aaaaa = (int *)arr2;
dwTickstart = GetTickCount();
for (int k = 0; k < TIMES; k++)
for (unsigned int i = 0; i != LOOP; i++) {
aaaaa[i] = i;
//cout << aaaaa[i] << endl;
}
dwTickend = GetTickCount();
cout << "ARRAY: " << dwTickend-dwTickstart << " microseconds." << endl;
dwTickstart = GetTickCount();
for (int k = 0; k < TIMES; k++)
for (unsigned int i = 0; i != LOOP; i++) { arr[i] = i - 1; }
dwTickend = GetTickCount();
cout << "ARRAY: " << dwTickend-dwTickstart << " microseconds." << endl;
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
test();
getchar();
return 0;
}
测试结果数据如下:
STD::ARRAY: 94 microseconds.
STD::ARRAY: auto:94 microseconds.
STD::ARRAY: auto:94 microseconds.
STD::vector:172 microseconds.
STD::vector: auto:390 microseconds.
ARRAY: 172 microseconds.
ARRAY: 172 microseconds.
1、以上三种方式中,使用STD::ARRAY时,耗时是最少的,
2、使用vector的时候,切记不要使用for (auto &v : vec)的方式,可能会造成大量的耗时。
3、原生数组耗时比较稳定。