系统:win7
ide:vs2012
今天闲来无事,想测试一下vector不同遍历方式性能有多少差别,先上代码
#include <iostream> #include <vector> #include <windows.h> using namespace std; int main() { // 创建vector,插入一百万条数据 std::vector<int> vecTest; const int VEC_SIZE = 1000000; vecTest.reserve(VEC_SIZE); for (int i = 0; i < VEC_SIZE; i++) { vecTest.push_back(i); } int tempNum = 0; const int TEST_TIMES = 100; LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); LARGE_INTEGER time0, time1, time2, time3; QueryPerformanceCounter(&time0); // 遍历方式一 for (std::vector<int>::iterator it = vecTest.begin(); it != vecTest.end(); ++it) { tempNum = *it; } QueryPerformanceCounter(&time1); // 遍历方式二 for (auto it : vecTest) { tempNum = it; } QueryPerformanceCounter(&time2); // 遍历方式三 size_t maxCount = vecTest.size(); for (size_t i = 0; i < maxCount; i++) { tempNum = vecTest[i]; } QueryPerformanceCounter(&time3); double sec0 = (double)time0.QuadPart / freq.QuadPart; double sec1 = (double)time1.QuadPart / freq.QuadPart; double sec2 = (double)time2.QuadPart / freq.QuadPart; double sec3 = (double)time3.QuadPart / freq.QuadPart; cout << "方式一 : " << sec1 - sec0 << endl; cout << "方式二 : " << sec2 - sec1 << endl; cout << "方式三 : " << sec3 - sec2 << endl; system("pause"); return 0; }
debug模式下运行三次,结果如下:
可以看到方式三的性能远胜于前两种,三和一差了十几倍,这个差别有点大了,不过别急我们再看看release模式下运行状况,如图:
刚开始看到这结果时我是这样的。怎么会是0,怎么可以是0,难道我的代码有bug!
然后我想这应该是被编译器优化了,那三段代码根本没执行,于是我在后面加了一句cout << tempNum << endl;
再试一试,看图:
哦耶,有结果了,可以看到三种方式差别很小,写代码时可以不用纠结用什么比较高效。