标签:style cto tar oop loop std .com 包含 clu
#include <iostream> #include <vector> #include <stdint.h> #include <ctime> int main() { const uint32_t loop = 1000000; std::vector<int32_t> vec; clock_t timeStart = 0; for (uint32_t i = 0; i < loop; ++i) { vec.push_back(i); } // test time use // 1.by index timeStart = clock(); for (uint32_t i = 0; i < vec.size(); ++i) { vec[i]; } std::cout << clock() - timeStart << "ms" << std::endl; // 2.by iterator timeStart = clock(); for (std::vector<int32_t>::const_iterator it = vec.begin(); it != vec.end(); ++it) { *it; } std::cout << clock() - timeStart << "ms" << std::endl; // 3.by auto iterator timeStart = clock(); for (auto it = vec.begin(); it != vec.end(); ++it) { *it; } std::cout << clock() - timeStart << "ms" << std::endl; getchar(); return 0; }
代码很简单,构建一个包含若干个整数的vector,分别按照三种方式遍历,统计消耗时间,结果如下:
可以发现,按照传统下标方式遍历的效率快的不是一星半点,虽然这种方式容易发成写错下标而造成越界的情况,但是在代码提效的时候,是一个不可忽视的点.
标签:style cto tar oop loop std .com 包含 clu
原文地址:http://www.cnblogs.com/tangxin-blog/p/6565118.html