-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator
55 lines (49 loc) · 1.04 KB
/
iterator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* 测试容器下标访问跟迭代器访问的性能差距
*
*
* 作者: elvis sun
* */
#include <iostream>
#include <vector>
#include <chrono>
using namespace std;
void indexTraverse(const vector<int> &vec)
{
vector<int>::size_type length = vec.size();
for (vector<int>::size_type i=0; i<length; ++i)
{
cout << vec[i];
}
cout << endl;
}
void iteratorTraverse(const vector<int> &vec)
{
for (vector<int>::const_iterator itr=vec.cbegin(); itr!=vec.cend(); ++itr)
{
cout << *itr;
}
cout << endl;
}
using ARG = const vector<int> &;
using PFUN = void (*)(ARG);
void check(PFUN pFun, ARG arg)
{
auto start = chrono::system_clock::now();
pFun(arg);
auto end = chrono::system_clock::now();
cout << chrono::duration_cast<chrono::microseconds>(end - start).count() << endl;
}
int main()
{
vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
check(indexTraverse, vec);
check(iteratorTraverse, vec);
return 0;
}
/** 运行结果
* 1234567890
* 66
* 1234567890
* 11
* */